Need to manage several objects in a project? Choose a data structure that matches how you will use them. Python’s built-in containers—lists, tuples, dictionaries, and sets—hold other objects. An integer or string is not a container. These structures are useful beyond any one application domain. section 3.0 section 1.4.1
Start with the access pattern:
- Use a list when you need to iterate through items; `enumerate` supplies positions alongside them. section 1.4.1
- Use a dictionary when keys should lead to values. Task titles, for example, can lead to urgency levels; the dictionary also lets you access its keys, values, or pairs. section 3.4
- Consider alternatives when lists and tuples no longer fit a specific project need; neither is automatically the right choice. section 4.5
Iterate through a list with positions
```python prime_numbers = [2, 3, 5] for num_pos, num in enumerate(prime_numbers, start=1): print(f"Prime Number #{num_pos}: {num}") ``` Output: ```text Prime Number #1: 2 Prime Number #2: 3 Prime Number #3: 5 ``` This avoids indexing the list through `range(len(prime_numbers))` merely to print each item’s position. section 1.4.1
Containers can hold more than simple values. A dictionary can map action names to functions, replacing a long chain of conditional branches with a lookup. A function parameter can also state its expected contents with a hint such as `list[Task]`, rather than just `list`. section 7.2.1 section 6.3.3
Watch for shared mutable objects when copying nested containers. A shallow copy duplicates the outer container but can still share an inner list; changing that list then affects both copies. Use a deep copy when the copies must be independent. section 10.3.2
Figure 10.5 The distinction between shallow and deep copies. In a shallow copy, the outmost data container (or any noncontainer object, such as a string) and its immutable contained objects are copied, but not the interior mutable objects, such as a list. By contrast, in a deep copy, the outmost container and all its interior objects have distinct copies. The gray boxes represent objects in memory.
The diagram distinguishes a copied outer container from an inner mutable object that a shallow copy still shares. section 10.3.2









