Python course · Module 4: Data structures · Lesson 19 of 63
Quick answer: Use a list for items in order that you will change, such as a shopping cart. Use a tuple for a fixed group of values that should not change, such as opening hours. Use a set when each item should appear only once and you mostly ask “is this item in it?”. Use a dict when you look values up by a key, such as a price by product name. Lists and tuples search item by item, while sets and dict keys find an item in about the same time however big they get.
In this lesson you will learn:
- how list, tuple, set and dict differ in order, changes, duplicates and lookup
- how much faster
inis on a set than on a list, measured withtimeit - when building a set is not worth it
- how to convert between the four types
- a short checklist for choosing the right one
Before you start: finish Lesson 18, Python Sets: add(), discard(), Union, Intersection and Removing Duplicates. This lesson also compares what you learned in Lesson 15 (lists), Lesson 16 (tuples) and Lesson 17 (dictionaries). All examples were tested on Python 3.14.6 and behave the same on Python 3.15.2, the newest release on python.org; only the timings change from run to run.
Table of Contents
The same data in four collections
Here is one shop’s sales, stored four ways:
sold_list = ["Pen", "Notebook", "Pen", "Ruler", "Pen"]
sold_tuple = ("Pen", "Notebook", "Pen", "Ruler", "Pen")
sold_set = {"Pen", "Notebook", "Pen", "Ruler", "Pen"}
sold_count = {"Pen": 3, "Notebook": 1, "Ruler": 1}
print(len(sold_list), len(sold_tuple), len(sold_set), len(sold_count))
print(sold_list[0], sold_tuple[-1], sold_count["Pen"])
print(sorted(sold_set))
5 5 3 3
Pen Pen 3
['Notebook', 'Pen', 'Ruler']
The list and the tuple keep all 5 sales, repeats included, in the order they happened, and you read them by position. The set keeps only the 3 different products and has no positions, so we print it with sorted(). The dict stores each product once as a key and answers a different question: how many of each were sold.
Python list vs tuple vs set vs dict: comparison table
| Feature | List | Tuple | Set | Dict |
|---|---|---|---|---|
| Written as | ["Pen", "Ruler"] | ("Pen", "Ruler") | {"Pen", "Ruler"} | {"Pen": 60} |
| Empty | [] | () | set() | {} |
| Keeps order | yes | yes | no | yes (insertion order) |
| Can change | yes | no | yes | yes |
| Duplicates | allowed | allowed | removed | keys unique, values can repeat |
| Read an item by | position, cart[0] | position, hours[0] | no positions; loop or in | key, prices["Pen"] |
Speed of in | slower as it grows | slower as it grows | fast | fast (checks keys) |
| Items must be hashable | no | no | yes | keys only |
“Hashable” roughly means the item cannot change, like a number, a string or a tuple; Lesson 18 explains it in “What can go inside a set?”. The dict order rule comes from the Built-in Types page: “Dictionaries preserve insertion order”, guaranteed since Python 3.7.
Finding an item
All four work with in, from Lesson 9. On a dictionary, in checks the keys:
sold_list = ["Pen", "Notebook", "Pen", "Ruler", "Pen"]
sold_set = {"Pen", "Notebook", "Ruler"}
prices = {"Pen": 60, "Notebook": 450, "Ruler": 40}
print("Ruler" in sold_list, "Ruler" in sold_set, "Ruler" in prices)
print(sold_list.index("Ruler"))
print(prices["Ruler"])
True True True
3
40
The answers are the same, but the work behind them is not. To answer "Ruler" in sold_list, Python compares "Ruler" with each item from the start until it finds a match; index() showed it was at position 3. A set or a dict uses the item’s hash value (the glossary says these types “use the hash value internally”) to jump almost straight to the right place. The official time complexity page lists x in l for a list and x in t for a tuple as O(n), meaning the time grows with the number of items, and x in s for a set and key in d for a dict as O(1), meaning it stays about the same. Those are average times; the page notes that in rare worst cases a set or dict lookup can also take O(n).
Speed test: in on a list vs a set
Let us measure it. The timeit module from the standard library times small pieces of code; import timeit loads it (Lesson 27 covers imports). We search for the last number, the worst case for a list, in lists and sets of four sizes:
import timeit
print(f"{'items':>9} {'list (microseconds)':>20} {'set (microseconds)':>20}")
for size in [1_000, 10_000, 100_000, 1_000_000]:
numbers_list = list(range(size))
numbers_set = set(numbers_list)
target = size - 1 # the last number: the list has to check every item before it
list_total = min(timeit.repeat("target in numbers_list", globals=globals(), repeat=5, number=100))
set_total = min(timeit.repeat("target in numbers_set", globals=globals(), repeat=5, number=100_000))
list_one = list_total / 100 * 1_000_000 # one search, in microseconds
set_one = set_total / 100_000 * 1_000_000
print(f"{size:>9,} {list_one:>20,.3f} {set_one:>20,.3f}")
items list (microseconds) set (microseconds)
1,000 5.095 0.019
10,000 51.510 0.019
100,000 560.328 0.019
1,000,000 6,602.064 0.019
How the code works:
timeit.repeat()runs the statement in quotesnumbertimes, does that 5 times (repeat=5), and returns the 5 total times in seconds.globals=globals()lets the timed code see our variablestarget,numbers_listandnumbers_set.- We keep the
min()of the 5 totals. The timeit documentation recommends this: the lowest value shows how fast the code can run, and higher values are “typically not caused by variability in Python’s speed, but by other processes interfering”. - Dividing by
numberand multiplying by 1,000,000 gives the time for one search in microseconds (millionths of a second).
Your numbers will be different. These come from one run on a Linux machine with an Intel Xeon 2.30 GHz processor. Your computer, your Python version and whatever else is running will change them. The pattern is what matters, and it matches the time complexity page. Each time the list got 10 times bigger, one search took roughly 10 times longer: about 5 microseconds for 1,000 numbers and about 6,600 microseconds (6.6 milliseconds) for a million. The set stayed at about 0.019 microseconds at every size.
When a set is not worth it
Building a set also takes time, because Python must hash every item. Is it worth building one just to search once?
import timeit
numbers_list = list(range(100_000))
target = 99_999
one_search = min(timeit.repeat("target in numbers_list", globals=globals(), repeat=5, number=100)) / 100
build_set = min(timeit.repeat("set(numbers_list)", globals=globals(), repeat=5, number=100)) / 100
print(f"one search in the list: {one_search * 1_000_000:,.0f} microseconds")
print(f"building the set once: {build_set * 1_000_000:,.0f} microseconds")
one search in the list: 535 microseconds
building the set once: 1,563 microseconds
In this run, building the set cost about as much as three worst-case list searches. So for one or two searches, just use in on the list. If your program checks many items, build the set once, before the loop, and search the set. With a few dozen items, the difference is too small to notice, so choose the type that makes your code clearest.
Converting between them
Each type’s name is also a function that converts other collections:
sold = ["Pen", "Notebook", "Pen", "Ruler", "Pen"]
print(tuple(sold))
print(sorted(set(sold)))
print(list(dict.fromkeys(sold)))
prices = {"Pen": 60, "Notebook": 450, "Ruler": 40}
print(list(prices))
print(list(prices.values()))
print(list(prices.items()))
('Pen', 'Notebook', 'Pen', 'Ruler', 'Pen')
['Notebook', 'Pen', 'Ruler']
['Pen', 'Notebook', 'Ruler']
['Pen', 'Notebook', 'Ruler']
[60, 450, 40]
[('Pen', 60), ('Notebook', 450), ('Ruler', 40)]
tuple(sold)keeps everything, in order.set(sold)removes duplicates but loses the order;list(dict.fromkeys(sold))removes duplicates and keeps the order.list(prices)gives the keys only. Usevalues()oritems()for the rest.
Going the other way, dict() needs pairs. Two matching lists can be paired with zip(), which, as the built-in functions page says, iterates “over several iterables in parallel, producing tuples with an item from each one”:
names = ["Pen", "Notebook", "Ruler"]
costs = [60, 450, 40]
prices = dict(zip(names, costs))
print(prices)
pairs = [("Eraser", 25), ("Backpack", 3200)]
print(dict(pairs))
{'Pen': 60, 'Notebook': 450, 'Ruler': 40}
{'Eraser': 25, 'Backpack': 3200}
Give dict() a list of plain strings and it fails, because each item must be a pair:
names = ["Pen", "Notebook", "Ruler"]
prices = dict(names)
Traceback (most recent call last):
File "/home/learner/python-course/err1_dict_from_list.py", line 2, in <module>
prices = dict(names)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
The message is confusing at first: Python treated the string "Pen" as a sequence of 3 characters, but it needed 2 things, a key and a value.
A checklist for choosing
Ask these questions in order:
- Do you look things up by a name or ID, like a price by product? Use a dict.
- Should each item appear only once, or do you mostly ask “is it in there?”? Use a set.
- Is it a fixed group of values that should never change, like a date or a pair of hours? Use a tuple.
- Anything else, especially items in order that you will add, remove or sort? Use a list.
Real programs mix them. Each comment below gives the reason for the choice:
opening_hours = ("09:00", "21:00") # fixed pair: tuple
prices = {"Pen": 60, "Notebook": 450, "Ruler": 40} # look up by name: dict
orders = ["Pen", "Notebook", "Pen", "Ruler", "Pen"] # in order, repeats allowed: list
customers = {"Ali", "Sara", "Ali", "Hina"} # each name once: set
total = 0
for item in orders:
total += prices[item]
print(f"Open {opening_hours[0]} to {opening_hours[1]}")
print("Orders:", len(orders), "Total:", total)
print("Different customers:", len(customers))
print("Did Sara buy anything?", "Sara" in customers)
Open 09:00 to 21:00
Orders: 5 Total: 670
Different customers: 3
Did Sara buy anything? True
The for loop from Lesson 12 walks the list in order and looks up each price in the dict. If you use Python 3.15 or newer, there is one more option: a built-in frozendict, a dictionary that cannot change, added by PEP 814 (What’s New in Python 3.15). It does not exist in Python 3.14, so this course does not use it yet.
Try it yourself
Exercise 1: Newsletter sign-ups
These emails signed up: ["ali@example.com", "sara@example.com", "ali@example.com", "hina@example.com"]. Pick the right type to count the different emails, and check whether sara@example.com signed up.
Exercise 2: Stock by name
You have products = ["Pen", "Notebook", "Backpack"] and stock = [40, 12, 5]. Turn them into a dict and print the stock of "Notebook".
Exercise 3: Tuple or set?
Make a tuple of the numbers 0 to 49,999 and a set of the same numbers. Use timeit to time a search for 49_999 in each.
Solutions
Solution 1
signups = ["ali@example.com", "sara@example.com", "ali@example.com", "hina@example.com"]
unique = set(signups)
print(len(signups), "sign-ups,", len(unique), "different emails")
print("sara@example.com" in unique)
4 sign-ups, 3 different emails
True
A set fits both jobs: it drops the repeated email and answers in quickly.
Solution 2
products = ["Pen", "Notebook", "Backpack"]
stock = [40, 12, 5]
stock_by_name = dict(zip(products, stock))
print(stock_by_name)
print(stock_by_name["Notebook"])
{'Pen': 40, 'Notebook': 12, 'Backpack': 5}
12
zip() pairs each product with its stock, and dict() turns the pairs into keys and values.
Solution 3
import timeit
numbers_tuple = tuple(range(50_000))
numbers_set = set(numbers_tuple)
target = 49_999
tuple_total = min(timeit.repeat("target in numbers_tuple", globals=globals(), repeat=5, number=100))
set_total = min(timeit.repeat("target in numbers_set", globals=globals(), repeat=5, number=100))
print(f"tuple: {tuple_total / 100 * 1_000_000:,.3f} microseconds per search")
print(f"set: {set_total / 100 * 1_000_000:,.3f} microseconds per search")
tuple: 248.658 microseconds per search
set: 0.019 microseconds per search
Your timings will differ, but the tuple is far slower here: like a list, it checks the items one after another (O(n) on the time complexity page).
Common mistakes
- Searching a big list again and again. There is no error, just a slow program. Build a set once and search that.
- Using a set when order matters.
set()loses the order of a list. Uselist(dict.fromkeys(items))to remove duplicates and keep the order. - Writing
{}for an empty set.{}is an empty dict; an empty set isset(). - Picking a tuple for data that changes.
opening_hours[1] = "22:00"givesTypeError: 'tuple' object does not support item assignment. Use a list, or make a new tuple. - Passing a plain list to
dict().dict(["Pen", "Notebook", "Ruler"])givesValueError: dictionary update sequence element #0 has length 3; 2 is required. Pair the items first withzip().
Frequently asked questions
When should I use a tuple instead of a list in Python?
Use a tuple for a fixed group of values that belong together and should not change, such as a date, a pair of coordinates or a function’s several return values. Use a list when items will be added, removed or sorted. A tuple of numbers or strings can also be a dict key or a set item, and a list cannot.
Is a set faster than a list in Python?
For in checks, yes: in our test a search in a set of a million numbers took about 0.019 microseconds, and in a list about 6,600 microseconds. Building the set takes time too, so it pays off when you search many times. For reading items by position, use a list; sets have no positions.
What is the difference between a set and a dictionary in Python?
Both use curly brackets and fast hashing, and both need hashable items or keys. A set stores single items, while a dict stores key and value pairs. Use a set to ask “is this item here?” and a dict to ask “what value belongs to this key?”.
Summary
- List: ordered, changeable, duplicates allowed; the default choice for items in order.
- Tuple: ordered and fixed; use it for values that belong together and should not change.
- Set: unordered, no duplicates, fast
in; dict: values looked up by unique keys, also fast. inon a list gets slower as the list grows, while sets and dicts stay fast, but building a set costs time too.- Convert with
list(),tuple(),set()anddict();dict()needs pairs, for example fromzip().
Next lesson
Next: Lesson 20, Python String Methods and Slicing: split(), join(), strip() and Reversing Strings.
Sources
- Time complexity of operations on built-in types (Python docs)
- timeit: Measure execution time of small code snippets (Python docs)
- Built-in Types: sets, dict, insertion order and the dict() constructor (Python docs)
- Built-in Functions: zip() (Python docs)
- Data Structures: Sets and Dictionaries (Python tutorial)
- What’s New in Python 3.15: frozendict, PEP 814 (Python docs)
- Glossary: hashable (Python docs)
- Python downloads page (python.org)





