Day 5: Lists, Tuples, Dictionaries & Sets
✅ Today you will learn
- Lists: index, slice, add, remove, sort
- Tuples for fixed records
- Dictionaries: key → value lookups
- Sets for unique values
- A list of dictionaries – the shape of real data
🏢 In the real world
An API from a delivery app returns orders as JSON – a list of dictionaries like {"order_id": 101, "city": "Pune", "amount": 450}. Before pandas, you must be comfortable reading and summarising exactly this structure.
Four containers at a glance
| Type | Syntax | Ordered | Changeable | Duplicates | Use for |
|---|---|---|---|---|---|
| list | [1, 2, 3] | Yes | Yes | Yes | A column of values |
| tuple | (1, 2) | Yes | No | Yes | A fixed record, e.g. (lat, lon) |
| dict | {"a": 1} | Yes* | Yes | Keys unique | Lookups, one record |
| set | {1, 2} | No | Yes | No | Unique values, membership |
Lists
orders = [1499, 299, 15999, 649, 2499] print(orders[0], orders[-1]) # first, last print(orders[1:4]) # slice: index 1, 2, 3 print(orders[:2], orders[-2:]) # first two, last two orders.append(899) # add at end orders.insert(0, 120) # add at position 0 orders.remove(299) # remove a value print(orders, len(orders)) print(sorted(orders), sorted(orders, reverse=True)[:3]) print(sum(orders), max(orders), min(orders))
Tuples – records that must not change
office = ("Bengaluru", 12.9716, 77.5946) # city, latitude, longitude
city, lat, lon = office # unpacking
print(city, lat, lon)
try:
office[0] = "Mysuru"
except TypeError as e:
print("Tuples cannot change:", e)Dictionaries – key → value
student = {"name": "Priya", "class": 12, "marks": [95, 97, 91]}
print(student["name"], student.get("city", "not given"))
student["city"] = "Jaipur" # add / update
student["class"] = "12-A"
print(student)
print(list(student.keys()))
for key, value in student.items():
print(f"{key:6} -> {value}")gst_rate = {"Grocery": 5, "Fashion": 12, "Electronics": 18, "Books": 0}
cart = [("Atta 10kg", "Grocery", 459), ("Earbuds", "Electronics", 1499), ("Kurta", "Fashion", 899)]
for item, cat, price in cart:
rate = gst_rate[cat]
print(f"{item:10} {cat:12} ₹{price:5} + {rate:2}% = ₹{price * (1 + rate / 100):,.2f}")Sets – unique values
visitors_mon = {"u1", "u2", "u3", "u5"}
visitors_tue = {"u2", "u3", "u4"}
print("Unique cities:", sorted(set(["Pune", "Delhi", "Pune", "Agra", "Delhi"])))
print("Both days :", sorted(visitors_mon & visitors_tue)) # sorted() = fixed order
print("Any day :", sorted(visitors_mon | visitors_tue))
print("Only Monday :", sorted(visitors_mon - visitors_tue))
print("u4" in visitors_mon)Printing a set can show items in a different order each run. Wrap it in sorted() when you need a stable, readable order.
List of dictionaries: real data shape
orders = [
{"id": 101, "city": "Pune", "category": "Grocery", "amount": 450},
{"id": 102, "city": "Delhi", "category": "Electronics", "amount": 15999},
{"id": 103, "city": "Pune", "category": "Fashion", "amount": 1299},
{"id": 104, "city": "Mumbai", "category": "Grocery", "amount": 780},
{"id": 105, "city": "Delhi", "category": "Grocery", "amount": 320},
]
city_total = {}
for o in orders:
city_total[o["city"]] = city_total.get(o["city"], 0) + o["amount"]
print(city_total)
big = [o["id"] for o in orders if o["amount"] > 1000]
print("Big orders:", big)
top = max(orders, key=lambda o: o["amount"])
print("Top order:", top["id"], top["city"], top["amount"])from collections import Counter categories = ["Grocery", "Electronics", "Fashion", "Grocery", "Grocery", "Fashion"] c = Counter(categories) print(c) print(c.most_common(2))
A list of dictionaries with the same keys is a table: each dict is a row and each key is a column. On Day 10 you will turn it into a pandas DataFrame with one line: pd.DataFrame(orders).
Copy trap
a = [10, 20, 30] b = a # same list, two names! b.append(40) print(a) c = a.copy() # real copy c.append(50) print(a, c)
🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
marks = [56, 78, 91, 45, 88, 67] print the top 3 marks and the average of the rest.Show solution
marks = [56, 78, 91, 45, 88, 67]
s = sorted(marks, reverse=True)
print("Top 3:", s[:3], "| rest avg:", sum(s[3:]) / len(s[3:]))orders list of dictionaries above, find the total amount per category.Show solution
orders = [{"category": "Grocery", "amount": 450}, {"category": "Electronics", "amount": 15999},
{"category": "Fashion", "amount": 1299}, {"category": "Grocery", "amount": 780}, {"category": "Grocery", "amount": 320}]
total = {}
for o in orders:
total[o["category"]] = total.get(o["category"], 0) + o["amount"]
print(total)Show solution
a = {"Aman", "Priya", "Rahul", "Sneha"}
b = {"Priya", "Kabir", "Sneha"}
print("Both:", sorted(a & b))
print("Only one:", sorted(a ^ b))Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
List vs tuple – when to use which?
Use a list for a collection that grows or changes (a column of values). Use a tuple for a fixed record whose parts have meaning by position, such as coordinates or a (key, value) pair; tuples can also be dictionary keys.
Why is checking membership faster in a set than in a list?
A set uses a hash table, so "x in s" takes about the same time regardless of size (O(1) on average). A list must be scanned item by item (O(n)).
Summary
- list = ordered, changeable column of values; slice with [start:stop].
- tuple = fixed record; dict = key → value lookup; set = unique values.
- A list of dicts is a table – the bridge to pandas.
- Use .copy() when you need an independent copy.
Day 6: read and write CSV and JSON files, handle errors gracefully and use Python modules.
