← Python EnglishChapter 06 of 13

Data Structures

## Learning Objectives - Master lists, tuples, sets, and dictionaries - Understand when to use each data structure - Learn common operations and methods ## Lists ### Creating Lists ```python empty = [] numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] nested = [[1, 2], [3, 4]] ``` ### Accessing Elements ```python fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple print(fruits[-1]) # cherry print(fruits[1:3]) # ['banana', 'cherry'] print(fruits[:2]) # ['apple', 'banana'] print(fruits[1:]) # ['banana', 'cherry'] ``` ### Modifying Lists ```python fruits = ["apple", "banana", "cherry"] # Add fruits.append("date") # At end fruits.insert(1, "apricot") # At index fruits.extend(["elderberry", "fig"]) # Add multiple # Remove fruits.remove("banana") # Remove by value popped = fruits.pop() # Remove and return last popped = fruits.pop(0) # Remove and return at index del fruits[0] # Delete at index fruits.clear() # Remove all # Modify fruits[0] = "avocado" # Change at index fruits[1:3] = ["blueberry", "cantaloupe"] # Replace slice ``` ### List Methods ```python numbers = [3, 1, 4, 1, 5, 9, 2, 6] numbers.sort() # In-place sort sorted(numbers) # Return new sorted list numbers.reverse() # In-place reverse numbers.index(4) # Index of first occurrence numbers.count(1) # Count occurrences numbers.copy() # Shallow copy ``` ### List Functions ```python numbers = [3, 1, 4, 1, 5, 9, 2, 6] len(numbers) # 8 min(numbers) # 1 max(numbers) # 9 sum(numbers) # 31 any(numbers) # True (truthy if any) all(numbers) # True (truthy if all) ``` ### List Comprehensions ```python squares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16] evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8] matrix = [[i * j for j in range(3)] for i in range(3)] # [[0, 0, 0], [0, 1, 2], [0, 2, 4]] ``` ## Tuples ### Creating Tuples ```python empty = () single = (42,) # Note the comma! point = (3, 4) mixed = (1, "hello", 3.14) nested = ((1, 2), (3, 4)) ``` ### Tuple Indexing ```python point = (3, 4, 5) print(point[0]) # 3 print(point[-1]) # 5 print(point[1:3]) # (4, 5) ``` ### Tuple Methods ```python point = (3, 4, 3, 5, 3) point.count(3) # 3 (count of 3) point.index(4) # 1 (first index of 4) ``` ### Why Tuples? - Immutable (can't modify) - Faster than lists - Can be used as dictionary keys - Protect data integrity ```python # Immutable - can't do this: # point[0] = 10 # TypeError! # Use as dict keys locations = { (40.7128, 74.0060): "New York", (51.5074, 0.1278): "London", } ``` ### Tuple Unpacking ```python x, y, z = (1, 2, 3) print(x, y, z) # 1 2 3 # Extended unpacking first, *middle, last = [1, 2, 3, 4, 5] print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5 ``` ## Sets ### Creating Sets ```python empty = set() # Not {} - that's a dict! numbers = {1, 2, 3, 4, 5} mixed = {1, "hello", 3.14} from_list = set([1, 2, 2, 3, 3]) # {1, 2, 3} ``` ### Set Operations ```python a = {1, 2, 3, 4} b = {3, 4, 5, 6} # Union print(a | b) # {1, 2, 3, 4, 5, 6} print(a.union(b)) # Same # Intersection print(a & b) # {3, 4} print(a.intersection(b)) # Same # Difference print(a - b) # {1, 2} print(a.difference(b)) # Same # Symmetric Difference print(a ^ b) # {1, 2, 5, 6} print(a.symmetric_difference(b)) # Same ``` ### Set Methods ```python s = {1, 2, 3} s.add(4) # Add one element s.update([5, 6]) # Add multiple s.remove(3) # Remove (raises error if not found) s.discard(10) # Remove (no error if not found) s.pop() # Remove and return arbitrary element s.clear() # Remove all ``` ### Set Comparisons ```python a = {1, 2, 3} b = {1, 2} c = {1, 2, 3, 4} print(a.issubset(b)) # False print(b.issubset(a)) # True (b is subset of a) print(a.issuperset(b)) # True (a is superset of b) print(a.isdisjoint(b)) # False (they share elements) ``` ### When to Use Sets - Remove duplicates - Membership testing (fast) - Mathematical set operations - Finding unique elements ```python # Remove duplicates items = [1, 2, 2, 3, 3, 3] unique = set(items) print(list(unique)) # [1, 2, 3] # Fast membership allowed = {"admin", "editor", "viewer"} if "admin" in allowed: print("Access granted") ``` ## Dictionaries ### Creating Dictionaries ```python empty = {} person = {"name": "Alice", "age": 25} dict(age=25, name="Bob") # From keyword args dict([("a", 1), ("b", 2)]) # From list of tuples {**{"a": 1}, **{"b": 2}} # From merging ``` ### Dictionary Access ```python person = {"name": "Alice", "age": 25, "city": "NYC"} print(person["name"]) # Alice print(person.get("name")) # Alice print(person.get("job", "Unknown")) # Unknown (default) ``` ### Modifying Dictionaries ```python person = {"name": "Alice", "age": 25} # Add/Update person["city"] = "NYC" person.update({"age": 26, "job": "Engineer"}) # Remove del person["job"] popped = person.pop("age") person.clear() ``` ### Dictionary Methods ```python person = {"name": "Alice", "age": 25, "city": "NYC"} person.keys() # dict_keys(['name', 'age', 'city']) person.values() # dict_values(['Alice', 25, 'NYC']) person.items() # dict_items([('name', 'Alice'), ...]) person.setdefault("country", "USA") # Set if not exists ``` ### Dictionary Views ```python person = {"name": "Alice", "age": 25} # Views reflect changes keys = person.keys() person["city"] = "NYC" print(list(keys)) # ['name', 'age', 'city'] ``` ### Dictionary Iteration ```python person = {"name": "Alice", "age": 25, "city": "NYC"} # Keys for key in person: print(key) # Key-value pairs for key, value in person.items(): print(f"{key}: {value}") ``` ### Dictionary Comprehensions ```python squares = {x: x ** 2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} words = ["apple", "banana", "cherry"] lengths = {word: len(word) for word in words} # {'apple': 5, 'banana': 6, 'cherry': 6} ``` ## Choosing Data Structures | Structure | Ordered | Mutable | Duplicates | Use Case | |-----------|---------|---------|------------|----------| | List | Yes | Yes | Yes | Sequence of items | | Tuple | Yes | No | Yes | Fixed data, coordinates | | Set | No | Yes | No | Unique items, math | | Dict | Yes* | Yes | Keys: No | Key-value mapping | *Note: Python 3.7+ dicts maintain insertion order ## Summary - **List**: Ordered, mutable, allows duplicates - use for sequences - **Tuple**: Ordered, immutable, allows duplicates - use for fixed data - **Set**: Unordered, mutable, no duplicates - use for unique items - **Dict**: Key-value pairs, ordered - use for mappings - List comprehensions: `[x for x in iterable]` - Dict comprehensions: `{k: v for k, v in items}` - Choose the right data structure for your needs

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →