‹ Back to Home

Python List, Dict, or Set? How to Pick the Right Data Structure Every Time

A list, a dict and a set all hold data. They do not hold it the same way. Pick wrong and a 10-line job becomes a 50-line mess — here is how a Chennai desk actually chooses.

Keerthika 8 min read
Follow on Google
Programming Python List, Dict, or Set? How to Pick the Right Data Structure Every Time 8 min left Follow on Google

TamilTech AI summary

  • Pick list, tuple, set or dict by the question you ask the data
  • Membership on a list walks every item; sets and dicts hash
  • Nested API JSON is dicts inside lists — walk it with .get()
  • Interviews still start with duplicates, frequency, two-sum and nested JSON

AI-assisted summary, checked by the TamilTech editorial team.

0:00
0:00
🔒 Listen is for subscribers. Subscribe

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_list walks every item. x in some_set does 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 change

Set — 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 doListSet / dict
Is X already there?Walks every itemHash lookup, stays cheap
Get one itemCheap by indexCheap by key
Add an itemappend is cheapadd / assign is cheap
Insert at the frontShifts everythingNot 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.

Frequently asked questions

5

Can I put a list inside a set or use it as a dict key?

No. Lists are mutable, so they are unhashable. Python raises TypeError. Convert the list to a tuple first if the sequence itself is the key.

Is a tuple faster than a list?

A little, sometimes, because it is fixed size. That is not why you pick it. You pick a tuple because the record should not change, or because you need a hashable key for a set or a dict.

When should I skip a comprehension?

When the rule does not fit in one breath, or when you are accumulating a total and a last-key-wins dict comprehension would lie to you. A plain for-loop is not a failure.

Why did checking x in my_list slow down my API?

A list membership test walks every element. At a few dozen items you will not notice. At a few lakh order IDs you will. Use a set or a dict.

How do I count frequencies without nested loops?

One dict. For each item, counts[item] = counts.get(item, 0) + 1. That is the whole pattern, and the one behind most count-the-SKUs interview questions.

Get tomorrow’s tech news on WhatsApp

One short update a day, free. Follow the TamilTech channel.

What do you think?

people reacted

Keerthika

TamilTech editorial team · 3,935 articles

Keerthika is an editor at TamilTech, the Tamil and English technology publication founded by Praveen Kumar S. She covers AI, smartphones, gadgets, EVs, startups and cybersecurity i...

More from Keerthika

Ask TamilTech on WhatsApp

Tech doubt? Ask in Tamil or English — our WhatsApp assistant answers from TamilTech articles in seconds.

Related stories

Comments (0)

| Supports **bold**, *italic*, `code`

Be the first to comment!

Next story You cannot clear a coding round without Big-O
TamilTech

TamilTech

Install app for faster access

Earn XP 🏆
WhatsApp
Notifications