Python Data Structures Cheat Sheet

Python Lists



Python
Copy
# Creating an empty list
empty_list = []

# Creating a list
my_list = [1, 2, 3, 4, 5]

Slicing
my_list[1:4]  # [2, 3, 4]

#Reversing
my_list[::-1]  # [5, 4, 3, 2, 1]

# Access elements by index
first_element = my_list[0]  # 1
last_element = my_list[-1]  # 8

# Modify elements by index
my_list[0] = 100  # [100, 2, 4, 5, 6, 7]

List Methods


Python
Copy
my_list = [1, 2, 3, 4, 5]

# Append a single element to the end
my_list.append(6)  # [1, 2, 3, 4, 5, 6]

# Insert an element at a specific position
my_list.insert(2, 10)  # [1, 2, 10, 3, 4, 5, 6]

# Extend the list with elements from another list or iterable
my_list.extend([7, 8])  # [1, 2, 10, 3, 4, 5, 6, 7, 8]
# Equivalent to: my_list += [7, 8]

# Remove the first occurrence of an element
my_list.remove(10)  # [1, 2, 3, 4, 5, 6, 7, 8]

# Remove an element at a specific position (and return it)
popped_element = my_list.pop(2)  # [1, 2, 4, 5, 6, 7, 8], popped_element is 3

# Remove the last element (and return it)
popped_element = my_list.pop()  # [1, 2, 4, 5, 6, 7], popped_element is 8

# Clear all elements from the list
my_list.clear()  # []

List Comprehensions


Python
Copy
# Basic list comprehension
squares = [x ** 2 for x in range(5)]  
# Output : [0, 1, 4, 9, 16]

# List comprehension with condition
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]  
# Output : [0, 4, 16, 36, 64]

Python Dictionary



Python
Copy
# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Creating an empty dictionary
empty_dict = {}

# Creating a dictionary using `dict` constructor
dict_from_pairs = dict([('name', 'Alice'), ('age', 25)])  
# Output : {'name': 'Alice', 'age': 25}

# Creating a dictionary with default values
default_dict = dict.fromkeys(['name', 'age', 'city'], 'unknown')  
# Output : {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}

# Accessing a value by key
name = my_dict['name']  
# Output : 'Alice'

# Accessing a value safely (returns `None` or a default value if the key does not exist)
age = my_dict.get('age')  
# Output : 25
gender = my_dict.get('gender', 'unknown')  
# Output : 'unknown'

# Modifying a value
my_dict['age'] = 26  
# Output : {'name': 'Alice', 'age': 26, 'city': 'New York'}

# Adding a new key-value pair
my_dict['gender'] = 'Female'  
# Output : {'name': 'Alice', 'age': 26, 'city': 'New York', 'gender': 'Female'}

Dictionary Methods


Python
Copy
# Remove a key-value pair by key 
# (raises `KeyError` if the key does not exist)
del my_dict['city']  
# Output : {'name': 'Alice', 'age': 26, 'gender': 'Female'}

# Remove a key-value pair by key and return the value 
# (returns `None` or a default value if the key does not exist)
age = my_dict.pop('age')  
# Output : 26, my_dict is now {'name': 'Alice', 'gender': 'Female'}

default_value = my_dict.pop('non_existing_key', 'default')  
# Output : 'default'

# Remove and return the last inserted key-value pair (LIFO order)
last_item = my_dict.popitem()  
# Output : ('gender', 'Female'), my_dict is now {'name': 'Alice'}

# Clear all elements from the dictionary
my_dict.clear()  
# Output : {}

# Get all keys as a view object
keys = my_dict.keys()  
# Output : dict_keys(['name', 'city', 'country'])

# Get all values as a view object
values = my_dict.values()  
# Output : dict_values(['Alice', 'Los Angeles', 'USA'])

# Get all key-value pairs as a view object
items = my_dict.items()  
# Output : dict_items([('name', 'Alice'), ('city', 'Los Angeles'), ('country', 'USA')])

Dictionary Comprehensions


Python
Copy
# Basic dictionary comprehension
squares = {x: x**2 for x in range(5)}  
# Output : {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Dictionary comprehension with a condition
my_dict = {1:"One", 2:"Two", 3:"Three", 4:"Four", 5:"Five"}
filtered_dict = {k: v for k, v in my_dict.items() if len(v) > 3}  
# Output : {3: 'Three', 4: 'Four', 5: 'Five'}

Python Set



Python
Copy
# Creating an empty set (Note: {} creates an empty dictionary, not a set)
empty_set = set()

# Creating a set with elements
my_set = {1, 2, 3, 4}

# Add a single element
my_set.add(5)  # {1, 2, 3, 4, 5}

# Add multiple elements (from another set, list, tuple, etc.)
my_set.update([6, 7])  # {1, 2, 3, 4, 5, 6, 7}

# Remove an element (throws KeyError if the element does not exist)
my_set.remove(2)  # {1, 3, 4, 5, 6, 7}

# Remove an element safely 
# Does not throw an error if the element does not exist
my_set.discard(4)  # {1, 3, 5, 6, 7}

# Remove and return an arbitrary element from the set.
# Removed_element is 1
removed_element = my_set.pop()  # {2, 4, 5, 6, 7, 8, 9}

# Clear all elements from the set
my_set.clear()  # set()

Python Set Operations


Python
Copy
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union: All unique elements from both sets
union_set = set1.union(set2)  # {1, 2, 3, 4, 5}
union_set = set1 | set2       # {1, 2, 3, 4, 5}

# Intersection: Elements common to both sets
intersection_set = set1.intersection(set2)  # {3}
intersection_set = set1 & set2              # {3}

# Difference: Elements in set1 but not in set2
difference_set = set1.difference(set2)  # {1, 2}
difference_set = set1 - set2            # {1, 2}

# Symmetric Difference: Elements in either set1 or set2 but not both
symmetric_difference_set = set1.symmetric_difference(set2)  # {1, 2, 4, 5}
symmetric_difference_set = set1 ^ set2                      # {1, 2, 4, 5}