Module 4 · Beginner · Lists, dictionaries, sets and tuples

List, tuple, set or dictionary? How to choose

How to choose between a list, tuple, set and dictionary in Python: a comparison table, speed of common operations, real examples, and questions to ask yourself.

By theprogrammers team · · 9 min read

You're building a small app for a college fest. You need the order in which teams registered, a fixed set of event timings, a check for whether a roll number has already entered, and a lookup from team name to captain. That's four jobs, and Python gives you four built-in collections. Choosing between a list, tuple, set or dictionary in Python is mostly about asking what you'll do with the data most often.

Pick well and your code is short and fast. Pick badly and you end up writing loops to find things, or fighting errors because something changed that shouldn't have. This lesson compares the four side by side and gives you a short set of questions that decides it.

What you need first: Python lists, Python dictionaries, tuples and sets.

Key terms

  • Ordered: items keep the position they were added in, and you can get them back by position.
  • Mutable: can be changed after it's created.
  • Duplicates allowed: the same value can appear more than once.
  • Lookup: finding an item, by position (items[3]), by key (ages["Ahana"]) or by value (x in items).
  • Time complexity: how the time an operation takes grows with the number of items, written in Big-O notation, such as O(1) (constant) or O(n) (grows with n).

The four collections side by side

ListTupleSetDictionary
Written as[1, 2, 3](1, 2, 3){1, 2, 3}{"a": 1}
OrderedYesYesNoYes (since Python 3.7)
Can changeYesNoYesYes
DuplicatesAllowedAllowedNot allowedKeys unique, values can repeat
Get byPositionPositionCan'tKey
in check speedSlow (O(n))Slow (O(n))Fast (O(1))Fast on keys (O(1))
Empty one[]()set(){}

Four questions that decide it

Ask these in order:

  1. Do you look things up by a name or ID? Use a dictionary. Roll number to student, product code to price, city to PIN code.
  2. Do you only care whether something is present, with no duplicates? Use a set. Who has already voted, which words appear in a document.
  3. Is it a fixed group of values that belong together and shouldn't change? Use a tuple. A (latitude, longitude) point, a (year, month, day) date, a database row.
  4. Otherwise, for an ordered sequence that grows, shrinks or gets sorted, use a list. Marks in a class, messages in a chat, a to-do list.

The fest app from the opening:

JobChoiceWhy
Teams in order of registrationListOrder matters and it grows
Event timingsTupleFixed; nobody should edit them in code
Roll numbers that have enteredSetOnly "seen or not", and fast checks
Team name to captainDictionaryLook up by name

Why the choice affects speed

Say you have 10 lakh registered phone numbers and must check incoming numbers against them. Here's the same check with a list and with a set:

import time

numbers = list(range(1_000_000))
number_set = set(numbers)
to_check = range(999_900, 1_000_000)     # 100 lookups near the end

start = time.perf_counter()
found = sum(1 for n in to_check if n in numbers)
list_seconds = time.perf_counter() - start

start = time.perf_counter()
found = sum(1 for n in to_check if n in number_set)
set_seconds = time.perf_counter() - start

print(f"List: {list_seconds:.2f} s   Set: {set_seconds:.5f} s")

We don't show an output because the timing depends on your computer. On a typical laptop the list takes a second or more, and the set takes a fraction of a millisecond. The list compares items one by one; the set jumps straight to the right place using a hash.

Here's how long common operations take as the collection grows:

OperationListSetDictionary
x in cO(n)O(1)O(1) on keys
Get by position c[i]O(1)not possiblenot possible
Get by key c[k]not possiblenot possibleO(1)
Add at end / add itemO(1)O(1)O(1)
Insert or remove at the startO(n)O(1)O(1)
SortO(n log n)not possiblenot possible directly

O(1) on sets and dictionaries is the average case; it's what you'll see in practice. If you often add and remove at both ends of a list, collections.deque does both in O(1). It's covered in the standard library module.

The same data, four ways

One small dataset, stored in each collection, to see what each is good at:

# List: ordered, allows repeats, good for "in what order?"
visits = ["Pune", "Goa", "Pune", "Delhi"]
print(visits[0], visits.count("Pune"))

# Tuple: a fixed record
trip = ("Pune", "Goa", "2026-12-20")
origin, destination, date = trip
print(destination)

# Set: unique, fast "have I been there?"
visited = set(visits)
print("Goa" in visited, len(visited))

# Dictionary: look up by city
visit_count = {}
for city in visits:
    visit_count[city] = visit_count.get(city, 0) + 1
print(visit_count["Pune"])
Pune 2
Goa
True 3
2

Combining them

Real programs mix collections. Choosing well usually means choosing the right outer and inner types:

# Dictionary of sets: which students are in which club, no duplicates
clubs = {"coding": {"Ahana", "Rohan"}, "music": {"Rohan", "Meera"}}
clubs["coding"].add("Ahana")                  # already there, no duplicate
print(sorted(clubs["coding"] & clubs["music"]))

# Dictionary with tuple keys: distance between two cities
distance = {("Mumbai", "Pune"): 148, ("Delhi", "Agra"): 233}
print(distance[("Mumbai", "Pune")])

# List of tuples: ordered, fixed records, easy to sort
results = [("Ahana", 88), ("Rohan", 72), ("Meera", 95)]
results.sort(key=lambda r: r[1], reverse=True)
print(results[0])
['Rohan']
148
('Meera', 95)

Nested lists, dictionaries and JSON goes further with mixed data.

Common wrong choices

  • A list for lookups by ID. Searching [s for s in students if s["roll"] == 104] on every request is slow. Build a dictionary keyed by roll number once.
  • A list for "already seen" checks in a loop. This quietly turns an O(n) program into O(n²). Use a set.
  • A dictionary where every value is True, like {"Ahana": True, "Rohan": True}. That's a set pretending to be a dictionary.
  • A tuple for data that changes, then converting it to a list and back again every time. Use a list.
  • Parallel lists: names = [...], marks = [...], cities = [...] kept in step by index. One delete and they drift apart. Use a list of dictionaries or tuples instead.

Beyond the built-ins

When none of the four fits perfectly, the standard library has more:

NeedUse
Count how often each item appearscollections.Counter
Dictionary that creates missing values automaticallycollections.defaultdict
Fast adding and removing at both ends (queues)collections.deque
Always get the smallest item fastheapq
A record with named fieldsdataclasses or typing.NamedTuple
Large tables of numbersNumPy arrays and pandas DataFrames

For data science, the rule of thumb is: built-in collections for small, mixed data and program logic; NumPy and pandas once you have thousands of rows of numbers.

Practice

For questions 1 to 4, choose a collection and say why.

  1. The 12 months of the year, in order, which your program only reads.
Show the answer

A tuple. The order matters and the data never changes. A list would also work, but a tuple says "this is fixed".

  1. Every word a user has already guessed in a word game, to stop repeat guesses.
Show the answer

A set. You only need "guessed or not", duplicates are pointless, and in must be fast.

  1. Item codes in a shop mapped to their prices.
Show the answer

A dictionary, {"A101": 49.0, ...}. You look prices up by code.

  1. The songs in a playlist, which the user can reorder and which may include the same song twice.
Show the answer

A list. Order matters, it changes, and duplicates are allowed.

  1. This code checks for duplicate roll numbers but is very slow on 1 lakh entries. Fix it.
rolls = [101, 102, 103, 102, 104]
seen = []
duplicates = []
for r in rolls:
    if r in seen:
        duplicates.append(r)
    seen.append(r)
print(duplicates)
Show the answer

r in seen searches a growing list, so the whole loop is O(n²). Make seen a set:

rolls = [101, 102, 103, 102, 104]
seen = set()
duplicates = []
for r in rolls:
    if r in seen:
        duplicates.append(r)
    seen.add(r)
print(duplicates)
[102]

Now each check is O(1) and the loop is O(n).

  1. Replace these parallel lists with a better structure, then print Rohan's marks.
names = ["Ahana", "Rohan", "Meera"]
marks = [88, 72, 95]
Show the answer

A dictionary keyed by name is the simplest fix here:

names = ["Ahana", "Rohan", "Meera"]
marks = [88, 72, 95]
marks_by_name = dict(zip(names, marks))
print(marks_by_name["Rohan"])
72

If each student had several fields, use a list of dictionaries instead.

Interview questions

When would you use a tuple instead of a list?

For a fixed group of related values that shouldn't change, such as coordinates or a database row, and when you need it as a dictionary key or set member. Tuples signal intent and are hashable when their items are.

Why are dictionary and set lookups O(1) on average?

Both are hash tables. Python computes a hash of the key, uses it to find a slot directly, and compares only the few items in that slot. Lists have no such index by value, so they must scan.

Can dictionary keys be lists?

No. Keys must be hashable, and lists are mutable, so {[1, 2]: "x"} raises TypeError: unhashable type: 'list'. Use a tuple instead.

Key takeaways

  • Lookup by name or ID: dictionary. Presence only, no duplicates: set. Fixed record: tuple. Everything else: list.
  • in is O(n) on lists and tuples but O(1) on sets and dictionary keys, which matters inside loops.
  • Avoid parallel lists; group related values into dictionaries or tuples.
  • Mix collections freely: dictionaries of sets, lists of tuples, dictionaries with tuple keys.
  • Reach for collections when the built-ins don't fit, and pandas or NumPy for large numeric data.

Frequently asked questions

Which Python data structure is fastest?

It depends on the operation. Sets and dictionaries are fastest for lookups by value or key. Lists and tuples are fastest for getting an item by position and for looping in order.

Are dictionaries ordered in Python?

Yes. Since Python 3.7, dictionaries keep the order in which keys were inserted. Sets still have no order.

Should I use a dictionary or a class for a record?

For quick scripts and data from JSON, a dictionary is fine. When the same kind of record appears all over a program, a class or dataclass gives you named fields, defaults and error checking. See Python classes and objects.

What to learn next

  1. Start working with text in cleaning and splitting text in Python.
  2. See how algorithms depend on these choices in Big-O notation.
  3. Model records properly with Python classes and objects.