Python Data Structures - Complete Functions & Methods Guide
1. String Methods
string.replace(old, new, count) # Replace occurrences of a substring
string.split(separator, maxsplit) # Split string into a list
string.rsplit(separator, maxsplit) # Split from right
string.lstrip(chars) # Remove leading spaces or specified chars
string.rstrip(chars) # Remove trailing spaces or specified chars
string.strip(chars) # Remove leading/trailing spaces or chars
string.find(substring, start, end) # Find position of substring (-1 if not found)
string.rfind(substring, start, end) # Find last occurrence of substring
string.index(substring, start, end) # Find index of substring, error if not found
string.rindex(substring, start, end) # Find last index of substring, error if not found
string.count(substring) # Count occurrences of substring
string.capitalize() # Capitalize first letter
string.title() # Convert to title case
string.upper() # Convert to uppercase
string.lower() # Convert to lowercase
string.swapcase() # Swap uppercase/lowercase
string.startswith(prefix) # Check if string starts with prefix
string.endswith(suffix) # Check if string ends with suffix
string.isalnum() # Check if all characters are alphanumeric
string.isalpha() # Check if all characters are alphabetic
string.isdigit() # Check if all characters are digits
string.isnumeric() # Check if all characters are numeric
string.isspace() # Check if all characters are whitespace
string.islower() # Check if all characters are lowercase
string.isupper() # Check if all characters are uppercase
string.istitle() # Check if string is title-cased
string.zfill(width) # Pad with leading zeros
string.center(width, fillchar) # Center string with padding
string.ljust(width, fillchar) # Left justify with padding
string.rjust(width, fillchar) # Right justify with padding
string.expandtabs(tabsize) # Expand tabs into spaces
string.splitlines(keepends) # Split string into lines
string.join(iterable) # Join elements of iterable with string
string.format(*args, **kwargs) # Format string
2. List Methods
list.append(element) # Add element at end
list.extend(iterable) # Extend list with another iterable
list.insert(index, element) # Insert element at index
list.remove(element) # Remove first occurrence of element
list.pop(index) # Remove and return element at index
list.clear() # Remove all elements
list.index(element, start, end) # Get index of first occurrence
list.count(element) # Count occurrences of element
list.sort(reverse=False, key=None) # Sort list in ascending/descending order
list.reverse() # Reverse the list
list.copy() # Return a shallow copy of the list
list.max() # Return the maximum value in the list
list.min() # Return the minimum value in the list
list.sum() # Return the sum of all elements in the list
3. Tuple Methods
tuple.count(element) # Count occurrences of element
tuple.index(element, start, end) # Find index of element
tuple.__len__() # Get length of tuple
tuple.__getitem__(index) # Get element at index
tuple.max() # Return the maximum value in the tuple
tuple.min() # Return the minimum value in the tuple
tuple.sum() # Return the sum of all elements in the tuple
4. Set Methods
set.add(element) # Add element to set
set.update(iterable) # Add multiple elements
set.remove(element) # Remove element (raises error if not found)
set.discard(element) # Remove element (no error if not found)
set.pop() # Remove and return an arbitrary element
set.clear() # Remove all elements
set.union(set2) # Return union of sets
set.intersection(set2) # Return intersection of sets
set.difference(set2) # Return difference of sets
set.symmetric_difference(set2) # Return symmetric difference
set.issubset(set2) # Check if subset
set.issuperset(set2) # Check if superset
set.copy() # Return a copy of the set
set.any() # Check if any element is True
set.all() # Check if all elements are True
5. Frozenset Methods (Immutable Set)
frozenset.union(set2) # Return union of sets
frozenset.intersection(set2) # Return intersection of sets
frozenset.difference(set2) # Return difference of sets
frozenset.symmetric_difference(set2) # Return symmetric difference
frozenset.issubset(set2) # Check if subset
frozenset.issuperset(set2) # Check if superset
6. Dictionary Methods
dict.keys() # Return keys of dictionary
dict.values() # Return values of dictionary
dict.items() # Return key-value pairs
dict.get(key, default) # Get value for key, return default if not found
dict.update(other_dict) # Update dictionary with another dictionary
dict.pop(key, default) # Remove key and return value
dict.popitem() # Remove and return last key-value pair
dict.clear() # Remove all elements
dict.copy() # Return a shallow copy
dict.setdefault(key, default) # Set default value for key
dict.fromkeys(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):
squares.append(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 grades.items() 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)