NullSector NullSector

So far we've worked with single values - one number, one string, one boolean. But real programs work with collections of data: lists of users, inventories of items, records of transactions, configurations, and much more.

Data structures are ways to organize multiple pieces of data. Think of them as different types of containers. Just as you wouldn't store soup in a paper bag or carry marbles in a colander, choosing the right data structure makes your code faster, cleaner, and easier to understand.

🏠 The Storage Room Metaphor

Lists are like numbered shelves - items in order, you can add/remove/reorganize.

Tuples are like sealed boxes - once packed, contents can't change.

Dictionaries are like labeled drawers - find things by name, not position.

Sets are like unique item collections - no duplicates allowed.

💡 The Four Core Structures

📋 Lists

Ordered, changeable collections. Use for sequences of similar items. Most common structure.

["apple", "banana", "cherry"]

🔒 Tuples

Ordered, unchangeable collections. Use for fixed data like coordinates or RGB colors.

(255, 128, 0)

📖 Dictionaries

Key-value pairs. Use for labeled data like user profiles or configurations.

{"name": "Alice", "age": 25}

🎯 Sets

Unordered, unique items. Use for membership testing and removing duplicates.

{1, 2, 3, 4, 5}

When to Use Each Structure

# ==================== DECISION GUIDE ==================== # LIST - When you need: # ✓ Ordered collection that can change # ✓ Duplicates are allowed # ✓ Access by index position # ✓ Process items in sequence shopping_cart = ["milk", "eggs", "bread", "eggs"] # Order matters, duplicates OK # TUPLE - When you need: # ✓ Fixed data that shouldn't change # ✓ Return multiple values from function # ✓ Dictionary keys (lists can't be keys!) # ✓ Slightly better performance than lists coordinates = (40.7128, -74.0060) # NYC location - shouldn't change # DICTIONARY - When you need: # ✓ Key-value associations # ✓ Fast lookup by name/key # ✓ Labeled, structured data user_profile = {"username": "alice99", "level": 42, "premium": True} # SET - When you need: # ✓ Unique items only (no duplicates) # ✓ Very fast membership testing # ✓ Set operations (union, intersection) unique_visitors = {"user1", "user2", "user3"}

Lists: Ordered Collections

Lists are the most commonly used data structure in Python. They hold ordered sequences of items that you can change, add to, or remove from. If you're not sure which structure to use, a list is usually a good starting point.

📝 The Shopping List Metaphor

A list is like a shopping list:

  • Items are in a specific order (first to last)
  • You can add new items anywhere
  • You can remove items or cross them out
  • You can change items (swap "milk" for "almond milk")
  • You can have duplicate items ("eggs" twice is fine)
  • The list grows or shrinks as needed

Creating Lists

# ==================== EMPTY LISTS ==================== # Two ways to create empty list shopping = [] also_empty = list() # ==================== LISTS WITH INITIAL ITEMS ==================== # List of strings fruits = ["apple", "banana", "cherry"] # List of numbers numbers = [1, 2, 3, 4, 5] prices = [19.99, 24.50, 9.99, 4.99] # List of booleans flags = [True, False, True, True] # Mixed types (allowed, but usually avoid) mixed = [1, "hello", 3.14, True, None] # ==================== CREATING FROM OTHER DATA ==================== # From a string (each character becomes an item) letters = list("hello") # ['h', 'e', 'l', 'l', 'o'] # From a range nums = list(range(1, 6)) # [1, 2, 3, 4, 5] evens = list(range(0, 10, 2)) # [0, 2, 4, 6, 8] # From another list (copy) original = [1, 2, 3] copy = list(original) # [1, 2, 3] - separate copy # ==================== NESTED LISTS ==================== # 2D list (list of lists) - like a grid or matrix matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Tic-tac-toe board board = [ ["X", "O", "X"], ["O", "X", "O"], ["X", " ", "O"] ] # List of student records students = [ ["Alice", 85, "A"], ["Bob", 72, "B"], ["Charlie", 91, "A"] ]

Accessing List Items

# ==================== INDEXING (SINGLE ITEM) ==================== fruits = ["apple", "banana", "cherry", "date", "elderberry"] # 0 1 2 3 4 # -5 -4 -3 -2 -1 # Positive indexing (from start, 0-based!) fruits[0] # "apple" (first item) fruits[1] # "banana" (second item) fruits[2] # "cherry" (third item) # Negative indexing (from end) fruits[-1] # "elderberry" (last item) fruits[-2] # "date" (second to last) fruits[-3] # "cherry" (third to last) # ==================== SLICING (MULTIPLE ITEMS) ==================== # Syntax: list[start:end] (end is NOT included!) fruits[1:3] # ["banana", "cherry"] (index 1 and 2, NOT 3) fruits[0:2] # ["apple", "banana"] (first two) fruits[2:5] # ["cherry", "date", "elderberry"] # ==================== SLICING SHORTCUTS ==================== # Omit start = start from beginning fruits[:3] # ["apple", "banana", "cherry"] (first 3) fruits[:1] # ["apple"] (first 1) # Omit end = go to end fruits[2:] # ["cherry", "date", "elderberry"] (from index 2) fruits[-2:] # ["date", "elderberry"] (last 2) # Omit both = copy entire list fruits[:] # ["apple", "banana", "cherry", "date", "elderberry"] # ==================== SLICING WITH STEP ==================== # Syntax: list[start:end:step] numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers[::2] # [0, 2, 4, 6, 8] (every 2nd item) numbers[::3] # [0, 3, 6, 9] (every 3rd item) numbers[1::2] # [1, 3, 5, 7, 9] (odd indices) # Negative step = reverse numbers[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reversed!) numbers[::-2] # [9, 7, 5, 3, 1] (reversed, every 2nd) # ==================== NESTED LIST ACCESS ==================== matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] matrix[0] # [1, 2, 3] (first row) matrix[1] # [4, 5, 6] (second row) matrix[0][0] # 1 (first row, first column) matrix[1][2] # 6 (second row, third column) matrix[-1][-1] # 9 (last row, last column)

Modifying Lists

# ==================== CHANGING ITEMS ==================== colors = ["red", "green", "blue"] # Change single item colors[0] = "yellow" # ["yellow", "green", "blue"] colors[-1] = "purple" # ["yellow", "green", "purple"] # Change multiple items with slicing numbers = [0, 1, 2, 3, 4, 5] numbers[1:4] = [10, 20, 30] # [0, 10, 20, 30, 4, 5] # Replace with different number of items numbers[1:4] = [100] # [0, 100, 4, 5] (3 items → 1) numbers[1:2] = [1, 2, 3, 4] # [0, 1, 2, 3, 4, 4, 5] (1 item → 4) # ==================== ADDING ITEMS ==================== fruits = ["apple", "banana"] # append() - Add ONE item to end fruits.append("cherry") # ["apple", "banana", "cherry"] # insert() - Add at specific position fruits.insert(0, "mango") # ["mango", "apple", "banana", "cherry"] fruits.insert(2, "orange") # ["mango", "apple", "orange", "banana", "cherry"] # extend() - Add MULTIPLE items from another list fruits.extend(["grape", "kiwi"]) # ["mango", "apple", "orange", "banana", "cherry", "grape", "kiwi"] # Concatenation with + more_fruits = fruits + ["lemon", "lime"] # Creates new list # ==================== REMOVING ITEMS ==================== colors = ["red", "green", "blue", "green", "yellow"] # remove() - Remove first occurrence of value colors.remove("green") # ["red", "blue", "green", "yellow"] # colors.remove("purple") # ValueError if not found! # pop() - Remove and return item last = colors.pop() # Returns "yellow", list is now ["red", "blue", "green"] first = colors.pop(0) # Returns "red", list is now ["blue", "green"] # del - Delete by index del colors[0] # ["green"] # clear() - Remove ALL items colors.clear() # [] # ==================== COMMON PATTERNS ==================== # Remove all occurrences of a value nums = [1, 2, 3, 2, 4, 2, 5] nums = [x for x in nums if x != 2] # [1, 3, 4, 5] # Remove by condition nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] nums = [x for x in nums if x % 2 != 0] # Keep odds: [1, 3, 5, 7, 9]

⚠️ Common List Pitfalls

  • Index out of range: fruits[100] crashes if list has fewer items
  • Off-by-one: Remember indices start at 0, not 1!
  • Modifying while looping: Don't remove items from a list while iterating over it
  • Shallow copy trap: new = old doesn't copy - both point to same list!

Essential List Methods

Lists come with powerful built-in methods for common operations. Mastering these will make you significantly more productive. Each method either modifies the list in place or returns a new value.

💡 In-Place vs Return Value

In-place methods (like sort(), reverse()) modify the original list and return None.

Return methods (like sorted(), reversed()) return a new list/iterator, leaving original unchanged.

Finding Items

# ==================== SEARCHING METHODS ==================== nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] # index() - Find position of first occurrence nums.index(4) # 2 (4 is at index 2) nums.index(5) # 4 (first 5 is at index 4) nums.index(1) # 1 (first 1 is at index 1) # nums.index(100) # ValueError! Not found # index() with start/end range nums.index(5, 5) # 8 (find 5 starting from index 5) nums.index(5, 5, 10) # 8 (find 5 between index 5 and 10) # count() - How many times does value appear? nums.count(5) # 3 (three 5s in the list) nums.count(1) # 2 nums.count(100) # 0 (not found = 0, no error) # ==================== MEMBERSHIP TESTING ==================== # "in" operator (very common!) 4 in nums # True 100 in nums # False 100 not in nums # True # Practical example valid_choices = ["rock", "paper", "scissors"] user_input = "rock" if user_input in valid_choices: print("Valid choice!") else: print("Invalid choice!") # ==================== SAFE SEARCHING ==================== # Check before accessing to avoid errors def safe_find(lst, value): """Find index safely, return -1 if not found.""" if value in lst: return lst.index(value) return -1 safe_find([1, 2, 3], 2) # 1 safe_find([1, 2, 3], 99) # -1

Sorting and Ordering

# ==================== SORTING ==================== numbers = [3, 1, 4, 1, 5, 9, 2, 6] # sort() - Sort IN PLACE (modifies original, returns None!) numbers.sort() # numbers is now [1, 1, 2, 3, 4, 5, 6, 9] print(numbers) # sort() with reverse numbers.sort(reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1] # sorted() - Return NEW sorted list (original unchanged) original = [3, 1, 4, 1, 5] new_sorted = sorted(original) print(original) # [3, 1, 4, 1, 5] - unchanged! print(new_sorted) # [1, 1, 3, 4, 5] - new list # ==================== CUSTOM SORTING ==================== # Sort by custom key function words = ["banana", "pie", "apple", "cherry"] # Sort by length words.sort(key=len) # ["pie", "apple", "banana", "cherry"] # Sort by last character words.sort(key=lambda w: w[-1]) # Sort case-insensitive names = ["alice", "Bob", "CHARLIE", "david"] names.sort(key=str.lower) # ["alice", "Bob", "CHARLIE", "david"] # Sort complex objects students = [ {"name": "Alice", "grade": 85, "age": 20}, {"name": "Bob", "grade": 92, "age": 19}, {"name": "Charlie", "grade": 85, "age": 21} ] # Sort by grade students.sort(key=lambda s: s["grade"]) # Sort by grade descending, then by age ascending students.sort(key=lambda s: (-s["grade"], s["age"])) # ==================== REVERSING ==================== nums = [1, 2, 3, 4, 5] # reverse() - Reverse IN PLACE nums.reverse() # [5, 4, 3, 2, 1] # reversed() - Return iterator (original unchanged) original = [1, 2, 3] rev_iter = reversed(original) rev_list = list(rev_iter) # [3, 2, 1] print(original) # [1, 2, 3] - unchanged! # Slicing trick (creates new list) nums = [1, 2, 3, 4, 5] rev = nums[::-1] # [5, 4, 3, 2, 1]

Copying Lists

# ==================== THE REFERENCE TRAP ==================== # WRONG way - both variables point to SAME list! original = [1, 2, 3] not_a_copy = original # Just another name for same list! not_a_copy.append(4) print(original) # [1, 2, 3, 4] - OOPS! Original changed! # ==================== PROPER COPYING ==================== original = [1, 2, 3] # Method 1: copy() method copy1 = original.copy() # Method 2: Slice entire list copy2 = original[:] # Method 3: list() constructor copy3 = list(original) # Now changes to copy don't affect original copy1.append(4) print(original) # [1, 2, 3] - Safe! print(copy1) # [1, 2, 3, 4] # ==================== DEEP COPY WARNING ==================== # Shallow copy only copies the outer list! nested = [[1, 2], [3, 4]] shallow = nested.copy() shallow[0][0] = 999 print(nested) # [[999, 2], [3, 4]] - Inner list affected! # For nested structures, use deepcopy import copy nested = [[1, 2], [3, 4]] deep = copy.deepcopy(nested) deep[0][0] = 999 print(nested) # [[1, 2], [3, 4]] - Safe!

Combining Lists

# ==================== JOINING LISTS ==================== a = [1, 2, 3] b = [4, 5, 6] # Concatenation with + (creates new list) c = a + b # [1, 2, 3, 4, 5, 6] print(a) # [1, 2, 3] - unchanged # extend() - Add all items from another list IN PLACE a.extend(b) # a is now [1, 2, 3, 4, 5, 6] # append() vs extend() list1 = [1, 2, 3] list1.append([4, 5]) # [1, 2, 3, [4, 5]] - Adds list as single item! list2 = [1, 2, 3] list2.extend([4, 5]) # [1, 2, 3, 4, 5] - Adds each item! # ==================== REPEAT WITH * ==================== zeros = [0] * 5 # [0, 0, 0, 0, 0] pattern = [1, 2] * 3 # [1, 2, 1, 2, 1, 2] # Initialize a grid grid = [[0] * 3 for _ in range(3)] # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Looping Through Lists

# ==================== BASIC LOOPS ==================== fruits = ["apple", "banana", "cherry"] # Simple for loop for fruit in fruits: print(fruit) # apple # banana # cherry # ==================== WITH INDEX ==================== # Using enumerate() - PREFERRED! for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # 0: apple # 1: banana # 2: cherry # Start from different number for i, fruit in enumerate(fruits, start=1): print(f"{i}. {fruit}") # 1. apple # 2. banana # 3. cherry # ==================== OTHER LOOP PATTERNS ==================== # Loop with range (when you need the index) for i in range(len(fruits)): print(f"Item {i} is {fruits[i]}") # Loop backwards for fruit in reversed(fruits): print(fruit) # cherry # banana # apple # Loop over multiple lists with zip names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] for name, age in zip(names, ages): print(f"{name} is {age} years old") # ==================== WHILE LOOP WITH LISTS ==================== # Process until empty tasks = ["task1", "task2", "task3"] while tasks: current = tasks.pop(0) # Remove first item print(f"Processing: {current}")

📋 Quick Reference: List Methods

Method Description Returns
append(x) Add item to end None
insert(i, x) Insert at position None
extend(list) Add all from another list None
remove(x) Remove first occurrence None
pop(i) Remove & return at index Item
index(x) Find first index of value int
count(x) Count occurrences int
sort() Sort in place None
reverse() Reverse in place None
copy() Shallow copy New list

Tuples: Immutable Sequences

Tuples are like lists but cannot be changed after creation. They're immutable - once you create a tuple, its contents are frozen forever. This makes them perfect for data that should never change, like coordinates, RGB colors, or database records.

📦 The Sealed Package Metaphor

A list is like a box you can open and modify.

A tuple is like a sealed package - you can see what's inside, but you can't change it.

Perfect for: coordinates, dates, fixed configurations, function return values.

Creating Tuples

# ==================== BASIC TUPLE CREATION ==================== # With parentheses coordinates = (10, 20) colors = ("red", "green", "blue") point_3d = (1.5, 2.0, -3.7) # Without parentheses (tuple packing) coords = 10, 20 # Also valid! person = "Alice", 25, "NYC" # Empty tuple empty = () also_empty = tuple() # ==================== SINGLE ITEM TUPLE (TRICKY!) ==================== # This is NOT a tuple! not_a_tuple = (42) # Just the number 42 in parentheses print(type(not_a_tuple)) # # This IS a tuple - note the comma! single = (42,) # Single-item tuple print(type(single)) # # Or without parentheses also_single = 42, # Also a single-item tuple # ==================== CREATING FROM OTHER DATA ==================== # From a list list_data = [1, 2, 3, 4, 5] tuple_data = tuple(list_data) # (1, 2, 3, 4, 5) # From a string letters = tuple("hello") # ('h', 'e', 'l', 'l', 'o') # From range nums = tuple(range(5)) # (0, 1, 2, 3, 4) # ==================== NESTED TUPLES ==================== # Tuple of tuples matrix = ( (1, 2, 3), (4, 5, 6), (7, 8, 9) ) # Mixed structures data = ( ("Alice", 25), ("Bob", 30), ("Charlie", 35) )

Accessing Tuple Elements

# ==================== INDEXING & SLICING ==================== # Same as lists! colors = ("red", "green", "blue", "yellow", "purple") # Positive indexing colors[0] # "red" colors[2] # "blue" # Negative indexing colors[-1] # "purple" colors[-2] # "yellow" # Slicing (returns new tuple) colors[1:3] # ("green", "blue") colors[:2] # ("red", "green") colors[2:] # ("blue", "yellow", "purple") colors[::2] # ("red", "blue", "purple") colors[::-1] # ("purple", "yellow", "blue", "green", "red") # ==================== NESTED ACCESS ==================== matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9)) matrix[0] # (1, 2, 3) matrix[1][2] # 6 matrix[-1][-1] # 9 # ==================== TUPLE METHODS ==================== nums = (1, 2, 2, 3, 3, 3, 4) # count() - How many times? nums.count(3) # 3 # index() - Where is it? nums.index(2) # 1 (first occurrence) # That's it! Only 2 methods (because tuples are immutable)

Why Tuples Are Immutable

# ==================== CANNOT MODIFY ==================== colors = ("red", "green", "blue") # These will ALL fail with TypeError: # colors[0] = "yellow" # Can't change item # colors.append("purple") # No append method # colors.remove("red") # No remove method # del colors[0] # Can't delete item # ==================== BUT YOU CAN REASSIGN THE VARIABLE ==================== colors = ("red", "green", "blue") colors = ("yellow", "orange") # This is OK - new tuple assigned # ==================== MUTABLE ITEMS INSIDE TUPLE ==================== # The tuple itself is immutable, but items inside CAN be mutable! weird = ([1, 2, 3], [4, 5, 6]) # Can't change the tuple # weird[0] = [10, 20] # TypeError! # BUT can modify the list inside! weird[0][0] = 100 # Works! weird is now ([100, 2, 3], [4, 5, 6]) # This is rarely useful - avoid it for clarity

Tuple Unpacking

# ==================== BASIC UNPACKING ==================== # Assign tuple items to variables at once point = (10, 20) x, y = point print(x) # 10 print(y) # 20 # Works with any length person = ("Alice", 25, "NYC", "Developer") name, age, city, job = person # ==================== SWAP VARIABLES ELEGANTLY ==================== # The classic way (needs temp variable) a = 1 b = 2 temp = a a = b b = temp # The Pythonic way (tuple unpacking!) a = 1 b = 2 a, b = b, a # Swap in one line! print(a, b) # 2 1 # ==================== IGNORE VALUES WITH _ ==================== data = ("Alice", 25, "alice@email.com", "555-1234") # Only need name and email name, _, email, _ = data # ==================== EXTENDED UNPACKING WITH * ==================== numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # Get first, last, and everything in between first, *middle, last = numbers print(first) # 1 print(middle) # [2, 3, 4, 5, 6, 7, 8, 9] (a list!) print(last) # 10 # Get first two and rest a, b, *rest = numbers print(a, b) # 1 2 print(rest) # [3, 4, 5, 6, 7, 8, 9, 10] # Get head and ignore rest head, *_ = numbers print(head) # 1

Function Return Values

# ==================== RETURNING MULTIPLE VALUES ==================== def get_stats(numbers): """Return min, max, and average of numbers.""" return min(numbers), max(numbers), sum(numbers) / len(numbers) # Returns a tuple! result = get_stats([1, 2, 3, 4, 5]) print(result) # (1, 5, 3.0) print(type(result)) # # Unpack directly minimum, maximum, average = get_stats([1, 2, 3, 4, 5]) print(f"Min: {minimum}, Max: {maximum}, Avg: {average}") # ==================== REAL-WORLD EXAMPLES ==================== def parse_email(email): """Split email into username and domain.""" parts = email.split("@") return parts[0], parts[1] username, domain = parse_email("alice@example.com") # username = "alice", domain = "example.com" def get_screen_size(): """Return screen dimensions.""" return 1920, 1080 width, height = get_screen_size() def divide_with_remainder(a, b): """Return quotient and remainder.""" return a // b, a % b quotient, remainder = divide_with_remainder(17, 5) # quotient = 3, remainder = 2

💡 Lists vs Tuples: When to Use Which

Use Lists When... Use Tuples When...
Data will change Data is fixed/constant
Need to add/remove items Return multiple values from function
Homogeneous data (same type) Heterogeneous data (mixed types)
['alice', 'bob', 'charlie'] ('Alice', 25, 'NYC')
Order matters, items similar Need dictionary keys

Dictionaries: Key-Value Pairs

Dictionaries store data as key-value pairs. Instead of accessing by index position, you access by a meaningful key - like a real dictionary where you look up words to find definitions. Dictionaries are one of Python's most powerful and frequently used data structures.

📖 The Real Dictionary Metaphor

Like a real dictionary:

  • Keys = Words you look up (must be unique!)
  • Values = Definitions you find (can be anything)

You don't say "give me the 5th word." You say "give me the definition of 'python'."

Keys provide INSTANT lookup - no searching through a list!

Creating Dictionaries

# ==================== BASIC CREATION ==================== # Empty dictionary empty = {} also_empty = dict() # Dictionary with initial data person = { "name": "Alice", "age": 25, "city": "New York" } # Single line (for short dicts) point = {"x": 10, "y": 20} # ==================== KEY TYPES ==================== # Keys must be immutable (hashable) # Good keys: strings, numbers, tuples data = { "text": "hello", # String key 42: "the answer", # Integer key 3.14: "pi", # Float key (0, 0): "origin", # Tuple key True: "yes" # Boolean key (but equals 1!) } # Bad keys: lists, dicts, sets (mutable = unhashable) # invalid = {[1, 2]: "list"} # TypeError! # ==================== VALUE TYPES ==================== # Values can be ANYTHING complex_data = { "numbers": [1, 2, 3, 4, 5], # List as value "nested": {"a": 1, "b": 2}, # Dict as value "active": True, # Boolean "callback": print, # Function as value! "none_value": None # None } # ==================== ALTERNATIVE CREATION METHODS ==================== # Using dict() constructor person = dict(name="Alice", age=25, city="NYC") # From list of tuples pairs = [("a", 1), ("b", 2), ("c", 3)] from_pairs = dict(pairs) # {"a": 1, "b": 2, "c": 3} # Using zip() with two lists keys = ["name", "age", "city"] values = ["Bob", 30, "LA"] zipped = dict(zip(keys, values)) # {"name": "Bob", "age": 30, "city": "LA"} # Dictionary comprehension squares = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Accessing Dictionary Values

# ==================== BASIC ACCESS ==================== person = {"name": "Alice", "age": 25, "city": "NYC", "job": "Developer"} # Square bracket notation person["name"] # "Alice" person["age"] # 25 # KeyError if key doesn't exist! # person["salary"] # KeyError: 'salary' # ==================== SAFE ACCESS WITH get() ==================== # get() returns None if key missing (no error!) person.get("name") # "Alice" person.get("salary") # None (no error!) # get() with default value person.get("salary", 0) # 0 (default if missing) person.get("salary", "Unknown") # "Unknown" person.get("name", "Unknown") # "Alice" (key exists, so returns actual value) # ==================== CHECKING KEY EXISTENCE ==================== # "in" operator checks KEYS, not values "name" in person # True "salary" in person # False "Alice" in person # False (Alice is a value, not a key!) # Check before access pattern if "salary" in person: print(person["salary"]) else: print("Salary not found") # Or use get() pattern (cleaner) salary = person.get("salary", "Not specified") print(f"Salary: {salary}") # ==================== NESTED ACCESS ==================== user = { "name": "Alice", "address": { "street": "123 Main St", "city": "NYC", "zip": "10001" }, "hobbies": ["reading", "coding", "gaming"] } # Chain access user["address"]["city"] # "NYC" user["hobbies"][0] # "reading" # Safe nested access city = user.get("address", {}).get("city", "Unknown") # Returns "NYC" if exists, "Unknown" if any key missing

Modifying Dictionaries

# ==================== ADD OR UPDATE ==================== person = {"name": "Alice", "age": 25} # Add new key-value pair person["city"] = "NYC" # {"name": "Alice", "age": 25, "city": "NYC"} # Update existing value person["age"] = 26 # {"name": "Alice", "age": 26, "city": "NYC"} # Same syntax for add or update - key determines which person["job"] = "Developer" # Add (key didn't exist) person["job"] = "Senior Dev" # Update (key exists now) # ==================== UPDATE MULTIPLE AT ONCE ==================== person = {"name": "Alice", "age": 25} # update() method - add/update multiple person.update({"age": 26, "city": "NYC", "job": "Dev"}) # {"name": "Alice", "age": 26, "city": "NYC", "job": "Dev"} # Can also use keyword arguments person.update(salary=100000, active=True) # ==================== SETDEFAULT ==================== # Set value only if key doesn't exist person = {"name": "Alice"} person.setdefault("age", 25) # Sets age to 25 person.setdefault("name", "Bob") # Does nothing (name exists) print(person) # {"name": "Alice", "age": 25} # ==================== REMOVING ==================== person = {"name": "Alice", "age": 25, "city": "NYC", "job": "Dev"} # del - Remove by key del person["job"] # {"name": "Alice", "age": 25, "city": "NYC"} # pop() - Remove and return value age = person.pop("age") # Returns 25, dict is now {"name": "Alice", "city": "NYC"} # pop() with default (no error if missing) salary = person.pop("salary", 0) # Returns 0, dict unchanged # popitem() - Remove and return last item (Python 3.7+) last = person.popitem() # Returns ("city", "NYC") # clear() - Remove all person.clear() # {} # ==================== MERGING DICTIONARIES ==================== dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} # Method 1: update() (modifies dict1) dict1.update(dict2) # Method 2: ** unpacking (Python 3.5+) merged = {**dict1, **dict2} # Creates new dict # Method 3: | operator (Python 3.9+) merged = dict1 | dict2 # Creates new dict

⚠️ Common Dictionary Mistakes

  • KeyError: Accessing missing key with [] raises error - use get() instead
  • Mutable keys: Lists can't be keys - use tuples instead
  • "in" checks keys: "Alice" in person checks keys, not values
  • Order assumption: Before Python 3.7, dicts didn't preserve order

Dictionary Methods & Patterns

Dictionaries have powerful methods for accessing and manipulating their contents. These patterns will help you work with dictionaries efficiently in real-world scenarios.

Keys, Values, and Items

# ==================== VIEW OBJECTS ==================== person = {"name": "Alice", "age": 25, "city": "NYC", "job": "Developer"} # keys() - Get all keys person.keys() # dict_keys(['name', 'age', 'city', 'job']) list(person.keys()) # ['name', 'age', 'city', 'job'] # values() - Get all values person.values() # dict_values(['Alice', 25, 'NYC', 'Developer']) list(person.values()) # ['Alice', 25, 'NYC', 'Developer'] # items() - Get all key-value pairs as tuples person.items() # dict_items([('name', 'Alice'), ('age', 25), ...]) list(person.items()) # [('name', 'Alice'), ('age', 25), ('city', 'NYC'), ('job', 'Developer')] # ==================== VIEW OBJECTS ARE LIVE ==================== # Views update when dictionary changes! keys = person.keys() print(keys) # dict_keys(['name', 'age', 'city', 'job']) person["country"] = "USA" print(keys) # dict_keys(['name', 'age', 'city', 'job', 'country'])

Looping Through Dictionaries

# ==================== BASIC LOOPS ==================== person = {"name": "Alice", "age": 25, "city": "NYC"} # Loop over keys (default) for key in person: print(key) # name # age # city # Loop over keys (explicit) for key in person.keys(): print(key) # Loop over values for value in person.values(): print(value) # Alice # 25 # NYC # ==================== LOOP OVER KEY-VALUE PAIRS ==================== # Most common pattern! for key, value in person.items(): print(f"{key}: {value}") # name: Alice # age: 25 # city: NYC # With formatting for key, value in person.items(): print(f" {key.upper()}: {value}") # ==================== LOOP WITH ENUMERATION ==================== for i, (key, value) in enumerate(person.items(), 1): print(f"{i}. {key} = {value}") # 1. name = Alice # 2. age = 25 # 3. city = NYC # ==================== CONDITIONAL PROCESSING ==================== scores = {"Alice": 85, "Bob": 92, "Charlie": 78, "Diana": 95} # Find all passing students for name, score in scores.items(): if score >= 80: print(f"{name} passed with {score}") # Create filtered dict passing = {name: score for name, score in scores.items() if score >= 80} # {'Alice': 85, 'Bob': 92, 'Diana': 95}

Dictionary Comprehensions

# ==================== BASIC COMPREHENSION ==================== # Syntax: {key_expr: value_expr for item in iterable} # Create dict from lists names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] people = {name: age for name, age in zip(names, ages)} # {'Alice': 25, 'Bob': 30, 'Charlie': 35} # Squares dict squares = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # ==================== TRANSFORM EXISTING DICT ==================== prices = {"apple": 1.00, "banana": 0.50, "cherry": 2.00} # Apply discount discounted = {item: price * 0.9 for item, price in prices.items()} # {'apple': 0.9, 'banana': 0.45, 'cherry': 1.8} # Uppercase keys upper_prices = {item.upper(): price for item, price in prices.items()} # {'APPLE': 1.0, 'BANANA': 0.5, 'CHERRY': 2.0} # ==================== WITH CONDITION ==================== # Filter by value expensive = {k: v for k, v in prices.items() if v > 0.75} # {'apple': 1.0, 'cherry': 2.0} # Filter by key selected = {k: v for k, v in prices.items() if k.startswith('a') or k.startswith('b')} # {'apple': 1.0, 'banana': 0.5} # ==================== SWAP KEYS AND VALUES ==================== original = {"a": 1, "b": 2, "c": 3} swapped = {v: k for k, v in original.items()} # {1: 'a', 2: 'b', 3: 'c'} # Careful: only works if values are unique and hashable!

Practical Example: User Database

# ==================== USER DATABASE PATTERN ==================== # Store users by ID (very common pattern!) users = { 1: {"name": "Alice", "email": "alice@email.com", "role": "admin", "active": True}, 2: {"name": "Bob", "email": "bob@email.com", "role": "user", "active": True}, 3: {"name": "Charlie", "email": "charlie@email.com", "role": "user", "active": False} } # ==================== LOOKUP BY ID (O(1) - instant!) ==================== def get_user(user_id): """Get user by ID, or None if not found.""" return users.get(user_id) user = get_user(2) if user: print(f"Found: {user['name']}") else: print("User not found") # ==================== SEARCH BY ATTRIBUTE ==================== def find_users_by_role(role): """Find all users with a specific role.""" return {uid: u for uid, u in users.items() if u["role"] == role} admins = find_users_by_role("admin") print(admins) # {1: {'name': 'Alice', ...}} def find_active_users(): """Get all active users.""" return [u for u in users.values() if u["active"]] active = find_active_users() for u in active: print(f" {u['name']} ({u['email']})") # ==================== ADD NEW USER ==================== def add_user(user_id, name, email, role="user"): """Add a new user to the database.""" if user_id in users: raise ValueError(f"User ID {user_id} already exists!") users[user_id] = { "name": name, "email": email, "role": role, "active": True } add_user(4, "Diana", "diana@email.com") # ==================== UPDATE USER ==================== def update_user(user_id, **changes): """Update user fields. Usage: update_user(1, email='new@email.com')""" if user_id not in users: raise ValueError(f"User ID {user_id} not found!") users[user_id].update(changes) update_user(1, email="newalice@email.com", role="superadmin") # ==================== DELETE USER ==================== def delete_user(user_id): """Remove a user from the database.""" return users.pop(user_id, None) deleted = delete_user(3) if deleted: print(f"Deleted user: {deleted['name']}")

Common Dictionary Patterns

# ==================== COUNTING OCCURRENCES ==================== text = "hello world" char_count = {} for char in text: char_count[char] = char_count.get(char, 0) + 1 print(char_count) # {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1} # Or use collections.Counter from collections import Counter char_count = Counter(text) # Same result! # ==================== GROUPING DATA ==================== students = [ {"name": "Alice", "grade": "A"}, {"name": "Bob", "grade": "B"}, {"name": "Charlie", "grade": "A"}, {"name": "Diana", "grade": "C"}, {"name": "Eve", "grade": "A"} ] # Group by grade by_grade = {} for student in students: grade = student["grade"] if grade not in by_grade: by_grade[grade] = [] by_grade[grade].append(student["name"]) print(by_grade) # {'A': ['Alice', 'Charlie', 'Eve'], 'B': ['Bob'], 'C': ['Diana']} # Or use defaultdict from collections import defaultdict by_grade = defaultdict(list) for student in students: by_grade[student["grade"]].append(student["name"]) # ==================== CACHING / MEMOIZATION ==================== cache = {} def expensive_calculation(n): """Cache results of expensive operations.""" if n in cache: return cache[n] # Simulate expensive operation result = n ** 2 # (would be complex in real life) cache[n] = result return result print(expensive_calculation(100)) # Calculates and caches print(expensive_calculation(100)) # Returns cached value

📋 Quick Reference: Dictionary Methods

Access

get(key, default) - Safe access

keys() - All keys

values() - All values

items() - Key-value pairs

Modify

update(dict) - Merge dicts

setdefault(k, v) - Set if missing

pop(key) - Remove & return

clear() - Remove all

Sets: Unique Collections

Sets are unordered collections with no duplicate values. They're incredibly fast for membership testing (is this item in the collection?) and perfect for operations like finding common items between collections, removing duplicates, or tracking unique values.

🎯 The Guest List Metaphor

A set is like a guest list at an exclusive party:

  • Each name can only appear once (no duplicates!)
  • Order doesn't matter (no assigned seating)
  • Checking if someone is on the list is instant
  • Easy to compare lists (who's at both parties?)

Creating Sets

# ==================== BASIC SET CREATION ==================== # Empty set - MUST use set(), NOT {} empty = set() # Empty set # not_a_set = {} # This creates an empty DICTIONARY! # Set with initial values numbers = {1, 2, 3, 4, 5} colors = {"red", "green", "blue"} # ==================== DUPLICATES ARE REMOVED ==================== # Duplicates automatically eliminated! nums = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4} print(nums) # {1, 2, 3, 4} # Great for removing duplicates from a list! names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Alice"] unique_names = set(names) print(unique_names) # {'Alice', 'Bob', 'Charlie'} # ==================== CREATING FROM OTHER DATA ==================== # From a string (each character becomes an item) letters = set("hello") # {'h', 'e', 'l', 'o'} - note: only one 'l'! # From a list list_data = [1, 2, 3, 4, 5] set_data = set(list_data) # {1, 2, 3, 4, 5} # From range evens = set(range(0, 10, 2)) # {0, 2, 4, 6, 8} # ==================== SET RULES ==================== # Items must be hashable (immutable) valid_set = {1, "hello", (1, 2, 3), 3.14, True} # Can't contain lists or dicts # invalid = {[1, 2, 3]} # TypeError! Lists are unhashable # invalid = {{"a": 1}} # TypeError! Dicts are unhashable # Use tuples instead of lists coordinates = {(0, 0), (1, 0), (0, 1), (1, 1)}

Set Operations - Adding and Removing

# ==================== ADDING ITEMS ==================== colors = {"red", "green", "blue"} # add() - Add single item colors.add("yellow") # {"red", "green", "blue", "yellow"} colors.add("red") # No effect - already exists! # update() - Add multiple items colors.update(["purple", "orange"]) # Add from list colors.update({"pink", "cyan"}) # Add from another set colors.update("abc") # Add 'a', 'b', 'c' # ==================== REMOVING ITEMS ==================== colors = {"red", "green", "blue", "yellow", "purple"} # remove() - Remove item (KeyError if not found!) colors.remove("yellow") # {"red", "green", "blue", "purple"} # colors.remove("orange") # KeyError! # discard() - Remove item (NO error if not found) colors.discard("purple") # {"red", "green", "blue"} colors.discard("orange") # No error, no change # pop() - Remove and return RANDOM item item = colors.pop() # Removes and returns some item print(f"Removed: {item}") # Which item? Can't predict! # clear() - Remove all items colors.clear() # set() # ==================== WHEN TO USE WHICH ==================== # Use remove() when item MUST exist (you want the error) # Use discard() when you don't care if it exists or not

Membership Testing (Super Fast!)

# ==================== THE POWER OF SETS: O(1) LOOKUP ==================== # Testing membership in a set is INSTANT, regardless of size! valid_users = {"alice", "bob", "charlie", "diana", "eve"} # Super fast - doesn't search through items one by one "bob" in valid_users # True (instant!) "zack" in valid_users # False (instant!) # ==================== SET VS LIST PERFORMANCE ==================== # List: O(n) - must check each item one by one # Set: O(1) - instant lookup using hashing # For small data: doesn't matter # For large data: HUGE difference! # Example: checking 1 million items # List: ~500,000 comparisons on average # Set: ~1 comparison (hash lookup) # ==================== PRACTICAL EXAMPLE ==================== # Validate user input valid_commands = {"start", "stop", "restart", "status", "help"} user_input = input("Enter command: ").lower().strip() if user_input in valid_commands: print(f"Executing: {user_input}") else: print(f"Unknown command: {user_input}") print(f"Valid commands: {', '.join(sorted(valid_commands))}")

Set Operations: Union, Intersection, Difference

# ==================== UNION: ALL ITEMS FROM BOTH ==================== a = {1, 2, 3, 4} b = {3, 4, 5, 6} # Union - all items from both sets a | b # {1, 2, 3, 4, 5, 6} a.union(b) # {1, 2, 3, 4, 5, 6} # Multiple sets c = {7, 8, 9} a | b | c # {1, 2, 3, 4, 5, 6, 7, 8, 9} a.union(b, c) # Same result # ==================== INTERSECTION: ITEMS IN BOTH ==================== # Items that appear in BOTH sets a & b # {3, 4} a.intersection(b) # {3, 4} # Multiple sets - must be in ALL a & b & {3, 4, 5} # {3, 4} # ==================== DIFFERENCE: ITEMS IN ONE BUT NOT OTHER ==================== # Items in a but NOT in b a - b # {1, 2} a.difference(b) # {1, 2} # Items in b but NOT in a b - a # {5, 6} # ==================== SYMMETRIC DIFFERENCE: IN ONE BUT NOT BOTH ==================== # Items in EXACTLY one set (not both) a ^ b # {1, 2, 5, 6} a.symmetric_difference(b) # ==================== SUBSET AND SUPERSET ==================== small = {1, 2} large = {1, 2, 3, 4, 5} # Is small a subset of large? (All small items in large?) small <= large # True small.issubset(large) # True # Is large a superset of small? large >= small # True large.issuperset(small) # True # Proper subset (subset but not equal) small < large # True large < large # False (equal, not proper subset) # Are sets disjoint? (No common items?) {1, 2}.isdisjoint({3, 4}) # True {1, 2}.isdisjoint({2, 3}) # False (2 is common)

Practical Uses for Sets

# ==================== REMOVE DUPLICATES FROM LIST ==================== names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Diana", "Alice"] # Method 1: Convert to set and back (loses order) unique = list(set(names)) # Order might change! # Method 2: Preserve order (Python 3.7+) unique_ordered = list(dict.fromkeys(names)) # ['Alice', 'Bob', 'Charlie', 'Diana'] # ==================== FIND COMMON ITEMS ==================== my_skills = {"Python", "JavaScript", "SQL", "HTML", "CSS"} job_requires = {"Python", "SQL", "Docker", "AWS", "React"} # What skills do I have that the job needs? matching = my_skills & job_requires print(f"Matching skills: {matching}") # {'Python', 'SQL'} # What do I need to learn? to_learn = job_requires - my_skills print(f"Need to learn: {to_learn}") # {'Docker', 'AWS', 'React'} # ==================== TRACK UNIQUE VISITORS ==================== visitors = set() def log_visit(user_id): """Track unique visitors.""" visitors.add(user_id) log_visit("user_001") log_visit("user_002") log_visit("user_001") # Duplicate, won't be added log_visit("user_003") print(f"Unique visitors: {len(visitors)}") # 3 # ==================== EFFICIENT FILTERING ==================== # Want to filter a large list by allowed values? # Use a set for the allowed values! allowed_domains = {"gmail.com", "outlook.com", "yahoo.com", "proton.me"} emails = [ "alice@gmail.com", "bob@company.com", "charlie@outlook.com", "diana@hotmail.com" ] # Filter to allowed domains only def get_domain(email): return email.split("@")[1] valid_emails = [e for e in emails if get_domain(e) in allowed_domains] # ['alice@gmail.com', 'charlie@outlook.com']

💡 Set Quick Reference

Operation Method Operator
Union a.union(b) a | b
Intersection a.intersection(b) a & b
Difference a.difference(b) a - b
Symmetric Diff a.symmetric_difference(b) a ^ b

Comprehensions: Elegant Data Creation

Comprehensions are a Pythonic way to create lists, dicts, and sets in a single line. They're more readable, often faster, and considered idiomatic Python. Master these and your code will look like it was written by a pro.

🏭 The Factory Metaphor

Traditional loops are like manually assembling products one by one.

Comprehensions are like an assembly line - define the process once, and it handles everything automatically.

Same result, but cleaner and often faster!

List Comprehensions

# ==================== BASIC SYNTAX ==================== # [expression for item in iterable] # Traditional way squares = [] for x in range(10): squares.append(x ** 2) # List comprehension (same result, one line!) squares = [x ** 2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # ==================== MORE EXAMPLES ==================== # Double each number numbers = [1, 2, 3, 4, 5] doubled = [n * 2 for n in numbers] # [2, 4, 6, 8, 10] # Convert to strings strings = [str(n) for n in numbers] # ['1', '2', '3', '4', '5'] # Call a function on each names = ["alice", "bob", "charlie"] upper_names = [name.upper() for name in names] # ['ALICE', 'BOB', 'CHARLIE'] capitalized = [name.capitalize() for name in names] # ['Alice', 'Bob', 'Charlie'] # Length of each string lengths = [len(name) for name in names] # [5, 3, 7] # ==================== WITH CONDITION (FILTERING) ==================== # [expression for item in iterable if condition] numbers = range(20) # Only even numbers evens = [x for x in numbers if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # Only odd numbers odds = [x for x in numbers if x % 2 != 0] # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] # Numbers greater than 10 big = [x for x in numbers if x > 10] # [11, 12, 13, 14, 15, 16, 17, 18, 19] # Combine transform AND filter # Squares of even numbers even_squares = [x ** 2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64] # ==================== WITH IF-ELSE (TRANSFORM) ==================== # [value_if_true if condition else value_if_false for item in iterable] # Note: if-else goes BEFORE for (this is a transform, not filter) numbers = range(10) # Label even/odd labels = ["even" if x % 2 == 0 else "odd" for x in numbers] # ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd'] # Pass/fail based on score scores = [85, 42, 91, 65, 78, 55] results = ["Pass" if s >= 60 else "Fail" for s in scores] # ['Pass', 'Fail', 'Pass', 'Pass', 'Pass', 'Fail'] # ==================== NESTED LOOPS ==================== # Flatten a 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9] # Cartesian product colors = ["red", "blue"] sizes = ["S", "M", "L"] combinations = [(c, s) for c in colors for s in sizes] # [('red', 'S'), ('red', 'M'), ('red', 'L'), ('blue', 'S'), ('blue', 'M'), ('blue', 'L')] # Multiplication table table = [[i * j for j in range(1, 4)] for i in range(1, 4)] # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Dictionary Comprehensions

# ==================== BASIC SYNTAX ==================== # {key_expr: value_expr for item in iterable} # Create dict from two lists names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] people = {name: age for name, age in zip(names, ages)} # {'Alice': 25, 'Bob': 30, 'Charlie': 35} # Squares dictionary squares = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # ==================== TRANSFORMING DICTIONARIES ==================== prices = {"apple": 1.00, "banana": 0.50, "cherry": 2.00, "date": 1.50} # Apply 10% discount discounted = {item: round(price * 0.90, 2) for item, price in prices.items()} # {'apple': 0.9, 'banana': 0.45, 'cherry': 1.8, 'date': 1.35} # Uppercase keys upper_prices = {k.upper(): v for k, v in prices.items()} # {'APPLE': 1.0, 'BANANA': 0.5, 'CHERRY': 2.0, 'DATE': 1.5} # Format values formatted = {k: f"${v:.2f}" for k, v in prices.items()} # {'apple': '$1.00', 'banana': '$0.50', 'cherry': '$2.00', 'date': '$1.50'} # ==================== WITH CONDITION ==================== # {key: value for item in iterable if condition} # Filter expensive items (> $1.00) expensive = {k: v for k, v in prices.items() if v > 1.00} # {'cherry': 2.0, 'date': 1.5} # Filter by key fruits_a_d = {k: v for k, v in prices.items() if k[0] in "abcd"} # {'apple': 1.0, 'banana': 0.5, 'cherry': 2.0, 'date': 1.5} # ==================== SWAP KEYS AND VALUES ==================== original = {"a": 1, "b": 2, "c": 3} swapped = {v: k for k, v in original.items()} # {1: 'a', 2: 'b', 3: 'c'} # ==================== CREATE FROM DIFFERENT SOURCES ==================== # From a list of tuples pairs = [("name", "Alice"), ("age", 25), ("city", "NYC")] person = {k: v for k, v in pairs} # {'name': 'Alice', 'age': 25, 'city': 'NYC'} # Index each item in a list items = ["apple", "banana", "cherry"] indexed = {i: item for i, item in enumerate(items)} # {0: 'apple', 1: 'banana', 2: 'cherry'} # Reverse: item as key, index as value positions = {item: i for i, item in enumerate(items)} # {'apple': 0, 'banana': 1, 'cherry': 2}

Set Comprehensions

# ==================== BASIC SYNTAX ==================== # {expression for item in iterable} # Unique squares (automatically no duplicates!) unique_squares = {x ** 2 for x in range(-5, 6)} # {0, 1, 4, 9, 16, 25} # First letters of words words = ["apple", "ant", "banana", "cherry", "avocado", "blueberry"] first_letters = {w[0] for w in words} # {'a', 'b', 'c'} # ==================== WITH CONDITION ==================== # Only vowels from a string text = "Hello World Programming" vowels = {char.lower() for char in text if char.lower() in "aeiou"} # {'a', 'e', 'i', 'o'} # Numbers divisible by 3 div_by_3 = {x for x in range(30) if x % 3 == 0} # {0, 3, 6, 9, 12, 15, 18, 21, 24, 27} # ==================== PRACTICAL USES ==================== # Get unique file extensions files = ["report.pdf", "data.csv", "photo.jpg", "notes.txt", "backup.csv"] extensions = {f.split(".")[-1] for f in files} # {'pdf', 'csv', 'jpg', 'txt'} # Unique domains from email list emails = ["a@gmail.com", "b@yahoo.com", "c@gmail.com", "d@outlook.com"] domains = {e.split("@")[1] for e in emails} # {'gmail.com', 'yahoo.com', 'outlook.com'}

Generator Expressions (Bonus)

# ==================== MEMORY-EFFICIENT COMPREHENSIONS ==================== # Generator expression: uses () instead of [] # Doesn't create the whole list in memory - generates items on demand # This creates a full list in memory (1 million items!) # big_list = [x ** 2 for x in range(1_000_000)] # Uses ~40MB memory # This creates a generator (almost no memory!) big_gen = (x ** 2 for x in range(1_000_000)) # Uses ~120 bytes # You can iterate over it, but only ONCE for num in big_gen: if num > 100: break # ==================== WHEN TO USE GENERATORS ==================== # Use generators when: # - Processing large datasets # - Only iterating once # - Need first few items, not all # Use lists when: # - Need random access (list[5]) # - Need to iterate multiple times # - Data is small enough to fit in memory # ==================== PRACTICAL EXAMPLE ==================== # Sum of squares without creating list total = sum(x ** 2 for x in range(1000)) # Note: no outer brackets needed when passing to a function! # Any/all with generator (memory efficient) numbers = range(1_000_000) has_negative = any(n < 0 for n in numbers) # False all_positive = all(n >= 0 for n in numbers) # True

⚠️ Comprehension Best Practices

  • Keep it simple: If it's too complex for one line, use a regular loop
  • Max one condition: Multiple conditions make comprehensions hard to read
  • Avoid side effects: Don't use comprehensions just to call functions
  • Name intermediate variables: If needed for clarity
# Too complex - use regular loop instead # BAD: [process(x) for x in data if x > 0 if check(x) for y in x.items() if y[1]] # GOOD: break it down filtered = [x for x in data if x > 0 and check(x)] result = [] for x in filtered: for key, value in x.items(): if value: result.append(process(x))

Choosing the Right Data Structure

Each data structure has strengths and weaknesses. Choosing the right one can make your code faster, cleaner, and easier to understand. Here's a comprehensive guide to help you decide.

🛠️ The Right Tool for the Job

You wouldn't use a hammer to screw in a bolt.

Similarly, using a list when you need key-value lookups (dict) or using a list to track unique items (set) leads to slower, messier code.

Learn the strengths of each structure!

Quick Decision Guide

If you need to... Use Why
Store ordered sequence, modify later List Flexible, ordered, supports duplicates
Store fixed data that won't change Tuple Immutable, safe, can be dict keys
Look up values by name/key Dictionary O(1) lookup by key
Check membership quickly Set O(1) membership test
Remove duplicates Set Only allows unique items
Store user profiles/records Dictionary Labeled fields like "name", "email"
Store coordinates (x, y, z) Tuple Fixed structure, immutable
Process items in order List Maintains insertion order
Return multiple values from function Tuple Clean unpacking syntax
Find common items between collections Set Built-in intersection operation
Count occurrences Dictionary Key = item, Value = count
Cache/memoize results Dictionary Key = input, Value = result

Performance Comparison

# ==================== TIME COMPLEXITY CHEAT SHEET ==================== # LISTS # - Access by index: O(1) - list[5] # - Search by value: O(n) - "x" in list, list.index("x") # - Append: O(1) - list.append(x) # - Insert at start: O(n) - list.insert(0, x) # - Delete by index: O(n) - del list[0] # DICTIONARIES # - Access by key: O(1) - dict["key"] # - Check if key: O(1) - "key" in dict # - Insert/update: O(1) - dict["key"] = value # - Delete: O(1) - del dict["key"] # SETS # - Check membership: O(1) - "x" in set # - Add: O(1) - set.add(x) # - Remove: O(1) - set.remove(x) # - Union/intersection: O(n+m) # ==================== PRACTICAL IMPLICATIONS ==================== # Searching for a user in a list of 1 million users: # List: ~500,000 comparisons average (slow!) # Dict: 1-2 lookups (instant!) # Always use the RIGHT structure for your use case!

Complete Example: Contact Manager

# ==================== contacts.py ==================== # A complete example using ALL data structures appropriately class ContactManager: """ Manages contacts using appropriate data structures: - Dictionary for storing contacts (fast lookup by name) - Set for tags (unique values, fast membership check) - List for search results (ordered, may have duplicates) - Tuple for contact info (immutable record) """ def __init__(self): # Dict: key=name, value=contact info self.contacts = {} # Set: all unique tags used self.all_tags = set() def add_contact(self, name, email, phone, tags=None): """Add a new contact.""" if name in self.contacts: raise ValueError(f"Contact '{name}' already exists!") # Tuple for immutable contact info contact_info = (email, phone) # Set for this contact's tags contact_tags = set(tags) if tags else set() self.contacts[name] = { "info": contact_info, # Tuple "tags": contact_tags # Set } # Update global tags self.all_tags.update(contact_tags) print(f"Added contact: {name}") def get_contact(self, name): """Get contact by name (O(1) lookup).""" contact = self.contacts.get(name) if contact: email, phone = contact["info"] # Tuple unpacking return { "name": name, "email": email, "phone": phone, "tags": list(contact["tags"]) # Convert set to list } return None def add_tag(self, name, tag): """Add a tag to a contact.""" if name not in self.contacts: raise ValueError(f"Contact '{name}' not found!") self.contacts[name]["tags"].add(tag) self.all_tags.add(tag) def search_by_tag(self, tag): """Find all contacts with a specific tag (returns list).""" # List comprehension - results are ordered return [ name for name, data in self.contacts.items() if tag in data["tags"] ] def find_common_tags(self, name1, name2): """Find tags that two contacts share (set intersection).""" if name1 not in self.contacts or name2 not in self.contacts: return set() tags1 = self.contacts[name1]["tags"] tags2 = self.contacts[name2]["tags"] return tags1 & tags2 # Set intersection! def get_all_emails(self): """Get list of all emails.""" return [data["info"][0] for data in self.contacts.values()] def export_contacts(self): """Export as list of tuples (immutable records).""" result = [] for name, data in self.contacts.items(): email, phone = data["info"] result.append((name, email, phone, tuple(data["tags"]))) return result def __len__(self): return len(self.contacts) def __str__(self): return f"ContactManager({len(self)} contacts, {len(self.all_tags)} unique tags)" # ==================== USAGE EXAMPLE ==================== if __name__ == "__main__": # Create manager manager = ContactManager() # Add contacts manager.add_contact( "Alice Smith", "alice@email.com", "555-0001", tags=["friend", "work", "python"] ) manager.add_contact( "Bob Johnson", "bob@email.com", "555-0002", tags=["work", "javascript"] ) manager.add_contact( "Charlie Brown", "charlie@email.com", "555-0003", tags=["friend", "python", "gaming"] ) # Fast lookup by name (O(1)) alice = manager.get_contact("Alice Smith") print(f"\nFound: {alice['name']} - {alice['email']}") # Find all work contacts work_contacts = manager.search_by_tag("work") print(f"\nWork contacts: {work_contacts}") # Find common interests common = manager.find_common_tags("Alice Smith", "Charlie Brown") print(f"\nAlice & Charlie common tags: {common}") # Get all unique tags print(f"\nAll tags: {manager.all_tags}") # Export as immutable records records = manager.export_contacts() for record in records: print(record) print(f"\n{manager}") # Output: # Added contact: Alice Smith # Added contact: Bob Johnson # Added contact: Charlie Brown # # Found: Alice Smith - alice@email.com # # Work contacts: ['Alice Smith', 'Bob Johnson'] # # Alice & Charlie common tags: {'friend', 'python'} # # All tags: {'friend', 'work', 'python', 'javascript', 'gaming'} # ('Alice Smith', 'alice@email.com', '555-0001', ('friend', 'work', 'python')) # ('Bob Johnson', 'bob@email.com', '555-0002', ('work', 'javascript')) # ('Charlie Brown', 'charlie@email.com', '555-0003', ('friend', 'python', 'gaming')) # # ContactManager(3 contacts, 5 unique tags)

💡 Summary: Data Structure Selection

📋 LIST

Use when: Ordered collection, may change, duplicates OK

Example: Shopping cart, to-do items, log entries

🔒 TUPLE

Use when: Fixed data, return values, dictionary keys

Example: Coordinates, RGB colors, database rows

📖 DICTIONARY

Use when: Key-value mapping, fast lookup, labeled data

Example: User profiles, config, cache

🎯 SET

Use when: Unique items, membership testing, set operations

Example: Tags, permissions, unique visitors

⚠️ Common Mistakes to Avoid

  • Using list for lookups: If you frequently check "is X in collection?", use a set!
  • Using list for key-value: If data has labels, use a dict, not nested lists
  • Forgetting immutability: Tuples can't be changed - that's the point!
  • Ignoring duplicates: Need unique values? Sets handle it automatically
  • Over-engineering: Start simple. You can always switch structures later.
← Chapter 03: Functions Next: Bonus Chapter - How To Code →