Fundamentals

Lists, Sets, Tuples and Disctionaries

TypeOrderedMutableDuplicatesExample
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.

python
1orders = [101, 102, 103]
2orders.append(104) # add at end
3orders.extend([105]) # add multiple
4orders.insert(1, 150) # add at index
5orders.remove(102) # remove first match
6orders.pop() # remove & return last
7orders.sort() # sort in place
8sorted(orders) # returns new sorted list

Use 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.

python
1row = (101, "Akash", 500)
2row[0] # 100 — OK, read
3row.append(1) # ❌ Error — can't modify

Use 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.

python
1ids = {101, 102, 101, 103} # → {101, 102, 103}
2ids.add(104)
3ids.discard(101) # no error if missing
4
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)

python
1user = {"id": 101, "name": "Akash"}
2user.get("email") # None (no KeyError)
3user.get("email", "n/a") # default value
4user.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

  1. List vs tuple — when to use each?
  2. remove() vs pop()?
  3. Why can't a set hold a list?
  4. sort() vs sorted()?
  5. dict["key"] vs dict.get("key")?
  6. How to dedupe records by ID?

Core takeaway:

text
1List → ordered + mutable + duplicates
2Tuple → ordered + immutable
3Set → unique values only
4Dict → key → value
Next TopicPython Functions