Lists, Sets, Tuples and Disctionaries
| Type | Ordered | Mutable | Duplicates | Example |
|---|---|---|---|---|
| List | ✅ | ✅ | ✅ | [1, 2, 3] |
| Tuple | ✅ | ❌ | ✅ | (1, 2, 3) |
| Set | ❌ | ✅ | ❌ | {1, 2, 3} |
| Dict | ✅* | ✅ | Keys: ❌ | {"id": 1} |
*Dicts preserve insertion order (Python 3.7+)
1. List
Definition: A list is an ordered, mutable collection that can hold duplicate values of any data type.
1orders = [101, 102, 103]2orders.append(104) # add at end3orders.extend([105]) # add multiple4orders.insert(1, 150) # add at index5orders.remove(102) # remove first match6orders.pop() # remove & return last7orders.sort() # sort in place8sorted(orders) # returns new sorted listUse for: ordered data you need to change (e.g., API results — often a list[dict]).
2. Tuple
Definition: A tuple is an ordered, immutable collection — once created, its values cannot be changed, added, or removed.
1row = (101, "Akash", 500)2row[0] # 100 — OK, read3row.append(1) # ❌ Error — can't modifyUse for: fixed data that shouldn't change (e.g., a DB row, coordinates).
3. Set
Definition: A set is an unordered collection of unique, hashable elements — duplicates are automatically removed.
1ids = {101, 102, 101, 103} # → {101, 102, 103}2ids.add(104)3ids.discard(101) # no error if missing4 5a, b = {1,2,3}, {3,4,5}6a.union(b) # {1,2,3,4,5}7a.intersection(b) # {3}8a.difference(b) # {1,2}Use for: deduplication, membership checks, comparing groups.
4. Dict
Definition: A dictionary is an unordered* collection of key-value pairs, where each key is unique and maps to a value. (Insertion order is preserved since Python 3.7)
1user = {"id": 101, "name": "Akash"}2user.get("email") # None (no KeyError)3user.get("email", "n/a") # default value4user.update({"age": 26})5user.pop("age")6 7for k, v in user.items():8 print(k, v)Use for: structured records — most JSON/API data maps here.
Quick Decision Guide
- Need to change order/values →
list - Need data that can't change →
tuple - Need only unique values →
set - Need key → value lookup →
dict - Processing API/JSON →
list[dict]
Common Interview Qs
- List vs tuple — when to use each?
remove()vspop()?- Why can't a set hold a list?
sort()vssorted()?dict["key"]vsdict.get("key")?- How to dedupe records by ID?
Core takeaway:
1List → ordered + mutable + duplicates2Tuple → ordered + immutable3Set → unique values only4Dict → key → value