list [ ]
Ordered, changeable, duplicates OK
products, rows, ids
tuple ( )
Ordered, fixed
(city, pincode), dict keys
dict { k: v }
Look up by key
one record; totals by key
set { }
Unique, unordered
distinct customers; fast 'in'
Lists
products = ["Headphones", "Smartwatch", "Charger"]
products.append("Phone Case") # add to the end
print(products[0], products[-1]) # first, last
print(products[1:3]) # slice: items 1 and 2
print(len(products), "Charger" in products)
print(sorted(products)) # new sorted list (original unchanged)Headphones Phone Case ['Smartwatch', 'Charger'] 4 True ['Charger', 'Headphones', 'Phone Case', 'Smartwatch']
Indexes start at 0; -1 is the last item. A slice [1:3] includes the start, excludes the end.
Tuples
location = ("Kolkata", 700130) # a tuple: fixed, can't be changed
city, pincode = location # unpacking
print(city, pincode)Kolkata 700130
location[0] = "Mumbai"TypeError: 'tuple' object does not support item assignmentDictionaries
order = {"order_id": 101, "product": "Headphones", "quantity": 1, "price": 1999}
print(order["product"]) # read by key
print(order.get("coupon", "NO_COUPON")) # safe read with a default
order["status"] = "DELIVERED" # add / change a key
for key, value in order.items():
print(f"{key} = {value}")Headphones NO_COUPON order_id = 101 product = Headphones quantity = 1 price = 1999 status = DELIVERED
print(order["coupon"])KeyError: 'coupon'Use d[key] when the key must exist (a missing key is a bug you want to see), d.get(key, default) when it's optional.
Records: a list of dicts
orders = [
{"order_id": 101, "customer": "Asha", "product": "Headphones", "amount": 1999, "status": "DELIVERED"},
{"order_id": 102, "customer": "Rahul", "product": "Smartwatch", "amount": 4999, "status": "DELIVERED"},
{"order_id": 103, "customer": "Asha", "product": "Charger", "amount": 1497, "status": "DELIVERED"},
{"order_id": 104, "customer": "Priya", "product": "Smartwatch", "amount": 4999, "status": "CANCELLED"},
]
delivered_total = sum(o["amount"] for o in orders if o["status"] == "DELIVERED")
print(f"Delivered revenue: ₹{delivered_total:,}")Delivered revenue: ₹8,495
sum(... for o in orders if ...) is a generator expression: it walks the records, filters and adds up without building a temporary list.
Sets
customers = {o["customer"] for o in orders} # set: unique values only
print(sorted(customers))
april = {"Asha", "Rahul", "Priya"}
may = {"Asha", "Priya", "Vikram"}
print(may - april) # in May, not April
print(sorted(april & may)) # in both
print(sorted(april | may)) # in either['Asha', 'Priya', 'Rahul']
{'Vikram'}
['Asha', 'Priya']
['Asha', 'Priya', 'Rahul', 'Vikram']Comprehensions
ids = [o["order_id"] for o in orders] # list comprehension
big = [o["order_id"] for o in orders if o["amount"] > 2000] # with a filter
by_id = {o["order_id"]: o["customer"] for o in orders} # dict comprehension
print(ids, big, by_id, sep="\n")[101, 102, 103, 104]
[102, 104]
{101: 'Asha', 102: 'Rahul', 103: 'Asha', 104: 'Priya'}Grouping and counting
from collections import Counter, defaultdict
revenue = defaultdict(int) # missing keys start at 0
for o in orders:
if o["status"] == "DELIVERED":
revenue[o["customer"]] += o["amount"]
print(dict(revenue))
print(Counter(o["status"] for o in orders)){'Asha': 3496, 'Rahul': 4999}
Counter({'DELIVERED': 3, 'CANCELLED': 1})This is GROUP BY in plain Python. Counter counts things in one line and has .most_common(n).
Sorting records
top = sorted(orders, key=lambda o: o["amount"], reverse=True)[:2]
for o in top:
print(o["order_id"], o["amount"])102 4999 104 4999
key= tells sorted what to compare; reverse=True sorts high to low. Sorting is stable: ties keep their original order.
| Need | Use | Speed of 'x in ...' |
|---|---|---|
| Ordered items you'll change | list | Slow (checks each item) |
| Fixed group of values | tuple | Slow |
| Lookup by key | dict | Fast (hash) |
| Unique values / membership | set | Fast (hash) |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Difference between list, tuple, set and dict?Fresher+
Q2Why must dict keys be immutable (hashable)?1–3 yrs+
Q3What is the time complexity of 'x in list' vs 'x in set'?1–3 yrs+
Q4How do you remove duplicates from a list but keep the order?1–3 yrs+
Q5How would you sum revenue per customer from a list of order dicts?3+ yrs+
Key takeaways
- ✓Pick the collection by how you use the data: order, change, lookup or uniqueness.
- ✓A list of dicts is plain Python's table.
- ✓Comprehensions, defaultdict and Counter replace many loops.
- ✓Next: control flow and functions to organise logic.
Frequently asked questions
List vs tuple: what's the difference?
A list can be changed (append, remove); a tuple can't. Use tuples for fixed groups of values (a city and its pincode) and as dictionary keys; lists for collections that grow.
When should I use a dictionary?
Whenever you look things up by a key: an order by its id, a customer's revenue by name. Lookups take the same tiny time no matter how big the dict is.
Why use a set?
To keep unique values and to test membership fast. Sets also do maths: difference (in May, not April), intersection, union.
What is a list comprehension?
A one-line way to build a list from another: [o['id'] for o in orders if o['amount'] > 2000]. It's faster and clearer than a loop with append for simple cases.
What's a 'list of dicts'?
The most common way to hold records in plain Python: each dict is a row, keys are column names. It's what csv.DictReader and most JSON APIs give you.
🧠 Quick check: lists, dicts and sets
1. Which keeps only unique values?
2. order.get('coupon', 'NONE') when there's no coupon key returns...
3. Fastest way to check if an id is in 1 million ids?
4. defaultdict(int) is useful because...
Checking your access…