Choose a list when you need order and duplicates, a set when uniqueness is the only question, a dict when you look up by name, and a tuple when the pair should stay locked. This piece walks Chennai and Coimbatore bays through those four Python boxes with carts, MAS–SBC tickets, UPI refs and SKU prices, shows why a list membership test crawls in production, and how a comprehension cuts the nested loop.
- A list keeps order and duplicates. A tuple is that list with a lock. A set keeps unique items. A dict maps a key to a value.
- Choose the box by the question you keep asking: position, uniqueness, or lookup by name.
x in some_listwalks every item.x in some_setdoes not. That gap shows up in production, not in tutorials.- Comprehensions replace the boring for-loop. Nested API JSON is just dicts inside lists — walk it with keys.
You know that 4 p.m. scene in a Chennai bay. Someone has a list of order IDs. They write a for-loop, then another loop inside it, then a flag called found. Forty lines later the function says yes or no.
That is not a syntax problem. That is a box problem.
Python hands you four everyday boxes: list, tuple, set, dict. Pick the one that matches the question you ask the data. The function shrinks.
What is the real difference between a list, a dict and a set?
A list is an ordered row of items. Duplicates are allowed. You talk to it with positions — first item, last item, slice from 2 to 5.
A tuple looks like a list, wears parentheses, and refuses to change. Pack a from-station and to-station. Pack a lat-long. Pack a record you should not edit by accident.
A set is a bag of unique values. It does not care about order the way a cart does. It cares about one question: have I already seen this?
A dict is a labelled drawer. The label is the key. The thing inside is the value. You do not hunt. You ask: what is the price of this SKU? Who owns this VPA?
People google python list vs dict because both can store stuff. They do not store it the same way. A list answers what sits at index 3. A dict answers what sits under this name.
Which one should you pick for this job?
Same kind of data you already touch — carts, tickets, UPI refs. Four tiny programs. Run them. Watch which box does the talking.
List — a cart that must keep order and allow two packets of milk:
cart = ['milk', 'bread', 'milk', 'eggs']
cart.append('curd')
print(cart[0], len(cart), cart.count('milk'))Tuple — a route that should not be edited in place, the way a ticket's from-to pair works:
route = ('MAS', 'SBC')
print(f'{route[0]} to {route[1]}')
# route[0] = 'MDU' # TypeError: tuples do not changeSet — webhook refs so a retry does not credit twice:
seen_refs = set()
incoming = ['UPI123', 'UPI456', 'UPI123']
for ref in incoming:
if ref in seen_refs:
print('duplicate', ref)
else:
seen_refs.add(ref)
print(sorted(seen_refs))Dict — price lookup by SKU, the way a billing counter actually works:
price_by_sku = {'MILK500': 58, 'BREAD': 45, 'EGGS12': 84}
print(price_by_sku.get('BREAD', 0))
print('MILK500' in price_by_sku)If you are looping through a list of pairs to find a name, you are using a dict that has not admitted it yet. Convert it. Delete the loop.
How do comprehensions cut the loop without hiding the logic?
A comprehension builds a list, set, or dict in one expression. It is still a loop. You just stopped decorating it with extra lines.
orders = [
{'city': 'Chennai', 'amount': 499},
{'city': 'Bengaluru', 'amount': 1299},
{'city': 'Chennai', 'amount': 250},
]
chennai_amounts = [o['amount'] for o in orders if o['city'] == 'Chennai']
cities = {o['city'] for o in orders}
print(chennai_amounts, sorted(cities))Read it left to right: take amount, from each order, only if the city is Chennai. That is the whole story.
Set comprehensions collect unique values. Dict comprehensions build a map — if the same key appears twice, the last one wins. For totals, a loop with .get() is clearer.
Skip the one-liner if the rule needs a comment to explain itself. Clarity beats clever on a Monday morning review.
What does each common operation actually cost?
You do not need an algorithms textbook on the desk. You need to stop scanning a lakh IDs with in on a list.
| What you do | List | Set / dict |
|---|---|---|
| Is X already there? | Walks every item | Hash lookup, stays cheap |
| Get one item | Cheap by index | Cheap by key |
| Add an item | append is cheap | add / assign is cheap |
| Insert at the front | Shifts everything | Not what a set is for |
A Python list is a dynamic array. Getting cart[3] is cheap. Asking if sku in cart is not, once the cart is not a cart but a day's worth of SKUs.
A set and a dict hash the key. Average lookup stays cheap when the bag grows. That is why processed_ids = set() shows up in every payment webhook that survived production.
append on a list is cheap. insert(0, x) is not — everything shifts. If you keep inserting at the front, you wanted a different structure, or you wanted append and a reverse at the end.
Sorting costs more as the list grows. Do it once, not inside another loop.
How do you walk nested data from an API response?
JSON from a payments or logistics API lands in Python as dicts and lists nested together. No special type. No magic.
payload = {
'status': 'ok',
'data': {
'items': [
{'sku': 'MILK500', 'qty': 2, 'price_inr': 58},
{'sku': 'BREAD', 'qty': 1, 'price_inr': 45},
]
},
}
items = payload.get('data', {}).get('items', [])
skus = [row['sku'] for row in items]
bill = sum(row['qty'] * row['price_inr'] for row in items)
print(skus, bill)Notice .get('data', {}). If the key is missing you get an empty dict, not a crash in the request worker at 11 p.m.
Then loop items. Pull sku, qty, price_inr by name. Sum with a generator expression if the formula is one line.
Deep nesting tempts a long chain of square-bracket keys. One missing key and the handler dies. Walk one level at a time. Check you actually have a list before you iterate.
Which mistakes get people into trouble?
Five classics. I still see them in PRs.
Using a list as a uniqueness filter. if ref in processed where processed is a list that grows with every webhook. Swap it for a set. Same code shape, different cost.
Putting a list inside a set, or using a list as a dict key. Lists can change, so they are unhashable. Python will raise TypeError. Freeze the key as a tuple first.
Changing a list while you iterate over it. Items get skipped. Build a new list, or use a comprehension that filters.
Keeping two parallel lists — names and ages — and hoping an insert hits both. One missed append and row 47 is a stranger. Use a list of dicts, or one dict keyed by id.
Default argument def add(item, bag=[]). That list is created once and shared across calls. Use None and create [] inside the function.
What do Indian companies actually grill you on?
Service-company first rounds still live here. Reverse a list, find the duplicate IDs, count how many times each SKU appears. Frequency is a dict job. Two nested loops will work on 20 items and embarrass you on 20,000.
Product-company rounds — Flipkart-style carts, Swiggy-style events, Razorpay-style webhooks — add one notch. Deduplicate with a set. Merge payloads with the | operator. Walk nested JSON. Two-sum with a dict, not two loops.
They are checking one instinct: when the question is uniqueness, do you reach for a set, or do you write another for-loop?
You will see variants of these four:
- Find duplicates in a list of transaction IDs — set, one pass.
- Count how often each SKU appears — dict.
- Two-sum on amounts against a target — dict of value to index.
- Unique visitors from an access log — set.
You will also get list vs tuple as a warm-up. Short answer: tuple when the record should not change and when you need a hashable key. List when you will append.
What should you do now?
Take a list of UPI payment dicts. Some ref values repeat because the app retried.
Write one function that returns three things: a set of unique refs, a dict of ref to total amount in paise, and a list of payments whose amount is above 50000 paise, original order kept.
Use a set, a dict, and one list comprehension. No nested loops. If it crosses 15 lines, you picked the wrong box.
That is the whole skill. Not syntax. Choosing the box so the syntax has less work to do.




Comments (0)
Be the first to comment!