0% found this document useful (0 votes)
16 views9 pages

Collections Functions Syntax and Comprehension

The document provides a comprehensive guide to Python data structures, detailing methods for strings, lists, tuples, sets, frozensets, and dictionaries. It also covers comprehensions, explaining their use cases and providing examples for list, set, dictionary, and tuple comprehensions. This guide serves as a reference for efficiently utilizing Python's built-in data structures and their associated methods.

Uploaded by

jagadeshrao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views9 pages

Collections Functions Syntax and Comprehension

The document provides a comprehensive guide to Python data structures, detailing methods for strings, lists, tuples, sets, frozensets, and dictionaries. It also covers comprehensions, explaining their use cases and providing examples for list, set, dictionary, and tuple comprehensions. This guide serves as a reference for efficiently utilizing Python's built-in data structures and their associated methods.

Uploaded by

jagadeshrao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Data Structures - Complete Functions & Methods Guide

1. String Methods

[Link](old, new, count) # Replace occurrences of a substring

[Link](separator, maxsplit) # Split string into a list

[Link](separator, maxsplit) # Split from right

[Link](chars) # Remove leading spaces or specified chars

[Link](chars) # Remove trailing spaces or specified chars

[Link](chars) # Remove leading/trailing spaces or chars

[Link](substring, start, end) # Find position of substring (-1 if not found)

[Link](substring, start, end) # Find last occurrence of substring

[Link](substring, start, end) # Find index of substring, error if not found

[Link](substring, start, end) # Find last index of substring, error if not found

[Link](substring) # Count occurrences of substring

[Link]() # Capitalize first letter

[Link]() # Convert to title case

[Link]() # Convert to uppercase

[Link]() # Convert to lowercase

[Link]() # Swap uppercase/lowercase

[Link](prefix) # Check if string starts with prefix

[Link](suffix) # Check if string ends with suffix


[Link]() # Check if all characters are alphanumeric

[Link]() # Check if all characters are alphabetic

[Link]() # Check if all characters are digits

[Link]() # Check if all characters are numeric

[Link]() # Check if all characters are whitespace

[Link]() # Check if all characters are lowercase

[Link]() # Check if all characters are uppercase

[Link]() # Check if string is title-cased

[Link](width) # Pad with leading zeros

[Link](width, fillchar) # Center string with padding

[Link](width, fillchar) # Left justify with padding

[Link](width, fillchar) # Right justify with padding

[Link](tabsize) # Expand tabs into spaces

[Link](keepends) # Split string into lines

[Link](iterable) # Join elements of iterable with string

[Link](*args, **kwargs) # Format string

2. List Methods

[Link](element) # Add element at end

[Link](iterable) # Extend list with another iterable

[Link](index, element) # Insert element at index


[Link](element) # Remove first occurrence of element

[Link](index) # Remove and return element at index

[Link]() # Remove all elements

[Link](element, start, end) # Get index of first occurrence

[Link](element) # Count occurrences of element

[Link](reverse=False, key=None) # Sort list in ascending/descending order

[Link]() # Reverse the list

[Link]() # Return a shallow copy of the list

[Link]() # Return the maximum value in the list

[Link]() # Return the minimum value in the list

[Link]() # Return the sum of all elements in the list

3. Tuple Methods

[Link](element) # Count occurrences of element

[Link](element, start, end) # Find index of element

tuple.__len__() # Get length of tuple

tuple.__getitem__(index) # Get element at index

[Link]() # Return the maximum value in the tuple

[Link]() # Return the minimum value in the tuple

[Link]() # Return the sum of all elements in the tuple

4. Set Methods
[Link](element) # Add element to set

[Link](iterable) # Add multiple elements

[Link](element) # Remove element (raises error if not found)

[Link](element) # Remove element (no error if not found)

[Link]() # Remove and return an arbitrary element

[Link]() # Remove all elements

[Link](set2) # Return union of sets

[Link](set2) # Return intersection of sets

[Link](set2) # Return difference of sets

set.symmetric_difference(set2) # Return symmetric difference

[Link](set2) # Check if subset

[Link](set2) # Check if superset

[Link]() # Return a copy of the set

[Link]() # Check if any element is True

[Link]() # Check if all elements are True

5. Frozenset Methods (Immutable Set)

[Link](set2) # Return union of sets

[Link](set2) # Return intersection of sets

[Link](set2) # Return difference of sets

frozenset.symmetric_difference(set2) # Return symmetric difference


[Link](set2) # Check if subset

[Link](set2) # Check if superset

6. Dictionary Methods

[Link]() # Return keys of dictionary

[Link]() # Return values of dictionary

[Link]() # Return key-value pairs

[Link](key, default) # Get value for key, return default if not found

[Link](other_dict) # Update dictionary with another dictionary

[Link](key, default) # Remove key and return value

[Link]() # Remove and return last key-value pair

[Link]() # Remove all elements

[Link]() # Return a shallow copy

[Link](key, default) # Set default value for key

[Link](iterable, value) # Create dictionary from keys with default value

dict.__getitem__(key) # Get value for key

dict.__setitem__(key, value) # Set value for key

dict.__delitem__(key) # Delete key from dictionary

1. Comprehensions in Python
Definition

Comprehensions in Python provide a concise and efficient way to create

collections such as lists, sets, tuples, and dictionaries. They are often used to

replace traditional loops and conditional statements, improving code readability

and performance.

Use Cases of Comprehensions

1. List Comprehensions - Used for filtering, mapping, and transforming lists.

2. Set Comprehensions - Useful for creating unique collections of elements.

3. Dictionary Comprehensions - Helps create and transform dictionaries

dynamically.

4. Tuple Comprehensions (Generator Expressions) - Efficient way to generate

tuple-like structures using generators.

1.1 List Comprehension

Definition

List comprehension is a concise way to create lists from iterables by applying a

transformation or filtering condition within a single line of code.

Comparison: List Comprehension vs. Traditional Loop

# Using traditional loop


squares = []

for x in range(1, 11):

[Link](x ** 2)

print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Using list comprehension

squares = [x ** 2 for x in range(1, 11)]

print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Example 2: Filtering even numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens = [x for x in numbers if x % 2 == 0]

print(evens) # [2, 4, 6, 8, 10]

# Example 3: Creating a list of characters from a string

word = "HELLO"

char_list = [char for char in word]

print(char_list) # ['H', 'E', 'L', 'L', 'O']

1.2 Set Comprehension

# Example 1: Convert a list to a set using comprehension


numbers_list = [1, 2, 2, 3, 4, 4, 5]

unique_numbers = {num for num in numbers_list}

print(unique_numbers) # {1, 2, 3, 4, 5}

# Example 2: Create a set of squares

squares_set = {x ** 2 for x in range(1, 6)}

print(squares_set) # {1, 4, 9, 16, 25}

# Example 3: Extract unique vowels from a sentence

sentence = "Hello, how are you?"

vowels = {char for char in sentence if char in "aeiouAEIOU"}

print(vowels) # {'e', 'o', 'a', 'u'}

1.3 Dictionary Comprehension

# Example 1: Swap keys and values in a dictionary

original_dict = {"a": 1, "b": 2, "c": 3}

swapped_dict = {v: k for k, v in original_dict.items()}

print(swapped_dict) # {1: 'a', 2: 'b', 3: 'c'}

# Example 2: Create a dictionary of squares

squares_dict = {x: x ** 2 for x in range(1, 6)}


print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Example 3: Filtering dictionary values

grades = {"Alice": 85, "Bob": 70, "Charlie": 90, "David": 60}

passed_students = {k: v for k, v in [Link]() if v >= 75}

print(passed_students) # {'Alice': 85, 'Charlie': 90}

1.4 Tuple Comprehension (Generator Expression)

# Example 1: Generate squares using a generator

squares_tuple = tuple(x ** 2 for x in range(1, 6))

print(squares_tuple) # (1, 4, 9, 16, 25)

# Example 2: Generate even numbers in a tuple

even_tuple = tuple(x for x in range(10) if x % 2 == 0)

print(even_tuple) # (0, 2, 4, 6, 8)

You might also like