Core Module
12 min forge
Python Data Structures
Lists, Dictionaries, Tuples, and Sets: Choosing the right tool.
Python Data Structures
π What is it
Python has four built-in collection types. Understanding their properties (ordered, changeable, and allowing duplicates) is crucial for technical interviews.
ποΈ Core Structures
- List: Ordered, changeable, allows duplicates (e.g.,
[1, 2, 2]). - Dictionary: Ordered (from Python 3.7+), changeable, no duplicates in keys (e.g.,
{"key": "value"}). - Tuple: Ordered, unchangeable (immutable), allows duplicates (e.g.,
(1, 2)). - Set: Unordered, unindexed, no duplicates (e.g.,
{1, 2}).
β‘ When to use
- List: For storing sequences of items where order matters.
- Dict: For fast lookups via keys (hashing).
- Tuple: For data that shouldn't change (safer memory allocation).
- Set: For membership testing and removing duplicates.
π§ Big-O Summary
| Structure | Access | Insert | Remove | Search |
|---|---|---|---|---|
| List | $O(1)$ | $O(n)$* | $O(n)$ | $O(n)$ |
| Dict | - | $O(1)$ | $O(1)$ | $O(1)$ |
| Set | - | $O(1)$ | $O(1)$ | $O(1)$ |
| *Amortized $O(1)$ for end insertions |
π» Code example
python Standard# List comprehension squares = [x**2 for x in range(10)] # Dict usage user = {"id": 1, "name": "Alice"} if "name" in user: print(user["name"]) # Set uniqueness nums = {1, 2, 2, 3} # Result: {1, 2, 3}
β Common mistakes
- Mutable Defaults: Using a list or dict as a default argument in a function (they are evaluated once at definition time).
- List Search: Using a list to check for membership in a loop (use a set for $O(1)$ lookup).
- Tuple Mod: Trying to modify a tuple (lead to
TypeError).