Python ships four core collections: list (ordered, mutable, allows duplicates), tuple (ordered, immutable), dict (key–value mapping), and set (unordered collection of unique items). Choosing the right one — and knowing slicing and lookup costs — covers most everyday Python.
The four collections
list [1,2,3]: ordered, mutable, indexable. tuple (1,2,3): like a list but immutable, so it's hashable and can be a dict key. dict {'a':1}: O(1) average key lookups, insertion-ordered (3.7+). set {1,2,3}: unique items, O(1) membership tests.
Core operations
nums = [1, 2, 3, 4]
print(nums[1:3]) # [2, 3] slicing returns a NEW list
nums.append(5) # [1,2,3,4,5]
ages = {"Asha": 30}
print(ages.get("Bob", 0)) # 0 (safe default; ages["Bob"] would KeyError)
unique = set([1, 1, 2, 3]) # {1, 2, 3}
print(2 in unique) # True (fast membership)⚡ The edge
- Slicing a list returns a new list (a shallow copy of that range), so nums[:] is a quick way to copy. Use a tuple when the sequence shouldn't change — it's also hashable, so it can be a dict key or set member.
- Use dict.get(key, default) to avoid KeyError when a key might be missing. Choose a set for uniqueness and fast in membership tests — it's far faster than scanning a list.
Worked example
When would you use a tuple instead of a list?
- When the sequence shouldn't change — immutability signals intent and prevents accidental modification.
- When you need a hashable sequence — e.g. as a dictionary key or an element of a set (lists can't be).
- Tuples are also slightly lighter. Use a list when you need to add, remove or reorder elements.
Answer: Use a tuple for a fixed sequence or a hashable key/set member; use a list when contents must change.
Worked example
How do you safely look up a key that might not exist in a dict?
- Indexing a missing key (d[k]) raises KeyError.
- Use d.get(k) which returns None (or a default you supply) instead of raising.
- Or check membership first with 'if k in d', or use collections.defaultdict for auto-defaults.
Answer: Use dict.get(key, default) (or 'in') instead of d[key], which raises KeyError on a missing key.
⚠ Watch out
- Shallow vs deep copy: nums[:] copies the list but not nested objects inside it.
- d[missing] raises KeyError; prefer .get() or in.
- Lists can't be dict keys or set members (unhashable); use a tuple.