Lists vs Dictionaries vs Sets in Python
Use a list to keep items in order, a dictionary to look up values by key, and a set to keep unique values or check membership. The right choice depends on what your program needs to do with the data.
A shopping list can contain bread twice. A price dictionary stores one price under each product name. A set tells you which products are in stock, without keeping a count. Those differences matter more than which collection is fastest.
New to the language? Start with the Python guide for variables and loops, then use these examples to choose a collection.
What Are Python Lists, Dictionaries, and Sets?
Python lists store items in order, dictionaries map keys to values, and sets store unique values without an order guarantee. All three let you add and remove entries.
A list is an ordered, changeable sequence written with square brackets. Every item has a position, positions are how you reach items, and the same value may appear as many times as you like.
A dictionary is a collection of key and value pairs written with braces. Every value is stored under a key you chose, keys are how you reach values, and each key appears at most once.
A set is an unordered collection of unique values, also written with braces but with no colons. A set has no positional indexes. It supports membership checks and operations such as finding values shared by two sets. Adding an existing value changes nothing.
arrivals = ["Ada", "Bo", "Ada"]
scores = {"Ada": 91, "Bo": 78}
attended = {"Ada", "Bo"}
print(arrivals, len(arrivals))
print(scores["Ada"])
print("Cleo" in attended) # Program output:
# ['Ada', 'Bo', 'Ada'] 3
# 91
# False Those three lines are the whole comparison in miniature. The list kept the repeat because arrivals repeat, the dictionary attached a number to a name, and the set answered a yes or no question about membership.
Quick Comparison
The behaviors below are what differ between the three types.
| Behavior | List | Dictionary | Set |
|---|---|---|---|
| Keeps insertion order | Yes | Yes, since 3.7 | No |
| Allows duplicates | Yes | Values only | No |
| Reached by | Position | Key | Membership only |
| Membership search cost | Grows with length | Flat, on average | Flat, on average |
| Contents must be hashable | No | Keys only | Yes |
| Stores | The item | Key and value | Unique items |
| Literal for an empty one | Square brackets | Braces | Written set() |
Python dictionaries preserve insertion order from Python 3.7 onward. Set membership and dictionary key lookups are fast on average, but hash collisions can make them slower.
Which Python Collections Preserve Order?
Python lists and dictionaries preserve insertion order; sets do not guarantee an order. Lists also let you access items by position or take a range with a slice. Adding or deleting items can change those positions.
log = ["opened", "edited", "saved"]
print(log[0], log[-1])
print(log[1:]) # Program output:
# opened saved
# ['edited', 'saved'] A Python dictionary remembers the order keys were added, and that order is for iterating, not for reaching things. There is no scores[0] unless 0 happens to be a key you created.
A set stores no order at all. It may print in a repeatable order inside one run, and nothing in the language promises that order between runs or between versions. Sort a set before comparing it to anything a person will read.
attended = {"Cleo", "Ada", "Bo"}
print(sorted(attended)) # Program output:
# ['Ada', 'Bo', 'Cleo'] The question to ask is whether the sequence is part of the data. Events in time, steps in a recipe, and rows from a file all carry order. A roster of who has permission does not.
How Do Python Lists, Dictionaries, and Sets Handle Duplicates?
Python lists keep duplicate values, sets remove duplicates, and dictionaries require unique keys but allow repeated values. Use a list when repeated entries matter, such as several votes for the same choice.
votes = ["yes", "no", "yes"]
tally = {"yes": 2, "no": 1}
options = {"yes", "no", "yes"}
print(len(votes), len(options))
print(tally["yes"]) # Program output:
# 3 2
# 2 A list keeps every repeat, which is correct when the repeat is a fact. Three votes are three votes, and collapsing them loses the count.
A set discards repeats on the way in, silently and immediately. That is exactly right for the set of options available and exactly wrong for the votes cast.
A dictionary sits between the two. Keys are unique, values are not, and the counting pattern turns a stream with repeats into a mapping from each distinct value to how often it appeared.
Which Python Collection Is Best for Lookups?
In Python, use a set for repeated membership checks and a dictionary to retrieve a value by key. A list works well for access by position, but finding a value may require checking every item. Sets and dictionaries avoid that full scan in the average case.
import timeit
setup = "big_list = list(range(200_000)); big_set = set(big_list)"
list_time = timeit.timeit("199_999 in big_list", setup=setup, number=100)
set_time = timeit.timeit("199_999 in big_set", setup=setup, number=100)
print(f"list: {list_time:.4f}s")
print(f"set: {set_time:.6f}s") Exact timings and the ratio vary between runs and between machines. The shape is what carries over. A worst-case list search on two hundred thousand items ordinarily takes far longer than the set lookup, and the gap widens as the collection grows.
Hash collisions can slow set and dictionary lookups. Building a set also takes time and memory, so converting a short list for a single check may not help. Measure the code if performance matters.
The other half of lookup is what comes back. A set tells you only whether the value is there, while a dictionary tells you what is attached to it. When the answer to "is this in here?" is immediately followed by "and what is its price?", the dictionary was the right container.
What Can Python Lists, Dictionaries, and Sets Contain?
Python lists and dictionary values can hold any object. Set members and dictionary keys must be hashable, such as strings, numbers, or tuples whose contents are all hashable. Lists and dictionaries themselves are not hashable.
pairs = [("London", "SW1"), ("Leeds", "LS1")]
lookup = {pair: index for index, pair in enumerate(pairs)}
unique = set(pairs)
print(lookup[("Leeds", "LS1")])
print(len(unique)) # Program output:
# 1
# 2 A list can contain other lists, but a set of lists raises TypeError: unhashable type: 'list'. Converting an inner list to a tuple works only if every item inside that tuple is also hashable. A tuple that still contains a list remains unhashable.
Tuples of hashable values work well for compound keys, such as a city and postal code used together to find a record.
The Same Job in All Three
A door log records each arrival, including repeat visits. Keep the original list to see who arrived first and last, build a dictionary to count visits, and use a set to find who attended.
entries = ["Ada", "Bo", "Ada", "Cleo", "Bo", "Ada"]
print(entries[0], entries[-1])
print(len(entries)) # Program output:
# Ada Ada
# 6 The list is the log itself. It answers "who was first?", "who was last?", and "how many entries were there?", and none of those questions survives de-duplication.
entries = ["Ada", "Bo", "Ada", "Cleo", "Bo", "Ada"]
visits = {}
for name in entries:
visits[name] = visits.get(name, 0) + 1
print(visits)
print(visits["Ada"]) # Program output:
# {'Ada': 3, 'Bo': 2, 'Cleo': 1}
# 3 The dictionary counts each person's visits. It keeps one key per person and stores the count as the value.
entries = ["Ada", "Bo", "Ada", "Cleo", "Bo", "Ada"]
expected = {"Ada", "Bo", "Dev"}
present = set(entries)
print(sorted(present))
print(sorted(expected - present))
print(sorted(present & expected)) # Program output:
# ['Ada', 'Bo', 'Cleo']
# ['Dev']
# ['Ada', 'Bo'] The set answers "who showed up at all?", and then answers two questions neither of the others can express in one line. Who was expected and never arrived is a difference, and who was both expected and present is an intersection.
Same data, three containers, three different capabilities. The containers differ in what they can say as well as in how fast they say it.
What Choosing Wrong Actually Costs
A List Doing a Set's Job
A list used to track values already seen can become slow. It works perfectly on test data and degrades quietly, because every membership test walks everything gathered so far.
incoming = ["a", "b", "a", "c", "b"]
seen = []
for item in incoming:
if item not in seen:
seen.append(item)
print(seen) # Program output:
# ['a', 'b', 'c'] Nothing is wrong with that output. The cost is that, in the worst case, processing a million distinct items does roughly half a trillion comparisons. Keep a set for membership checks alongside the list, or use list(dict.fromkeys(incoming)) to remove duplicates from hashable values while keeping their first-seen order.
A Dictionary Doing a List's Job
A dictionary keyed by 0, 1, and 2 is a list wearing a disguise. It costs more memory, it cannot be sliced, sorting it means rebuilding it, and the keys can drift out of sequence when an entry is deleted.
This one is more expensive to undo than the first, because every read site in the code was written against key access and the keys may have been serialized into stored data. Catch it at design time by asking whether any key means something other than "the position of this item".
Losing Order and Repeated Values in a Set
Converting a list to a set loses its original order and repeated values. Both are discarded at the moment of conversion, and neither can be recovered from the set afterwards.
The damage shows up late, usually as an output whose sequence changes for no visible reason, and the repair is to go back to whatever produced the data. Convert to a set at the point where a question is about membership, not as a general-purpose tidy-up.
Should You Use a Python List, Dictionary, or Set?
Choose a Python list for positions and repeated entries, a dictionary for key-value pairs, and a set for unique values and membership checks. You can combine collections when one alone does not cover the job.
Choose a list when:
- The sequence is part of the data, such as events, steps, or rows read from a file.
- Repeats are facts rather than noise, such as votes cast or entries in a log.
- You reach items by position, or take ranges of them with slices.
- The contents include things that cannot be hashed, such as other lists.
Choose a dictionary when:
- Each item has a natural name or identifier, and you reach it by that name.
- Something is attached to each unique thing, such as a count, a price, or a record.
- You are counting or grouping, such as visits per person or customers per city.
- The data arrived as JSON, where objects map onto dictionaries directly.
Choose a set when:
- The only question is whether a value is present.
- Duplicates are meaningless and should disappear on the way in.
- You want to compare two collections with union, intersection, or difference.
- Nothing needs to be attached to each member and no order needs keeping.
When two of those lists describe your case, use two containers. A list beside a set is the standard answer to "ordered, and de-duplicated", and it is a design rather than a compromise.
Choose a Collection for the Job
Ask what question the collection has to answer, not what the data happens to look like. Order and repeats point to a list, a name with something attached points to a dictionary, and a plain yes or no about membership points to a set.
Frequently Asked Questions
Can Python lists, dictionaries, and sets be used together?
Python lists, dictionaries, and sets can be used together. For example, keep a list of arrivals and a set of names already seen. The list preserves arrival order, while the set makes repeated membership checks quick.
Is a Python set a dictionary without values?
A Python set stores unique values without pairing them with separate values, unlike a dictionary. Both sets and dictionaries use hashing to find entries, but they are different types with different methods. Set members and dictionary keys must be hashable.
Are sets ordered in modern Python?
Python sets do not guarantee insertion order. Dictionaries have guaranteed insertion order since Python 3.7, but sets have not. Use sorted(my_set) when you need a predictable display order and the items can be compared.
How do you convert between Python lists, dictionaries, and sets?
To convert Python collections, use set(items) for unique values, list(my_set) for a list, or dict(pairs) for key-value pairs. A set does not preserve the original order. Converting a dictionary with list(d) or set(d) keeps its keys, not its values.
Which uses less memory in Python: a list, dictionary, or set?
For the same number of entries, a CPython list usually uses less container memory than a set or dictionary. Sets and dictionaries need extra space for fast lookups. The exact amount varies, and sys.getsizeof() counts the container separately from the objects it refers to.
When should you use a Python tuple instead of a list?
A Python tuple is an immutable sequence, useful for a fixed group such as a coordinate pair. Unlike a list, a tuple cannot have items added, removed, or replaced. A tuple can be a dictionary key or set member only when all its contents are hashable.
Next Steps
- List and Dict Comprehensions in Python - build any of these from another iterable in one expression.
Sources
-
[1]
Data Structures(docs.python.org)
-
[2]
Set Types: set, frozenset(docs.python.org)
-
[3]
Glossary: hashable(docs.python.org)
-
[4]
Design and History FAQ(docs.python.org)
Read Next
A comprehension builds a list or a dictionary from an existing iterable in one expression. The syntax for both forms, filtering, conditional values, nesting, and the cases where a plain loop is the better answer.
A Python list keeps items in the order you put them and lets you change that order later. How to create one, index and slice it, add and remove items, copy it safely, and recognize the jobs a list is wrong for.
What is Python used for, and who uses it? Is it slow, how do AI agents change learning it, Python or JavaScript first, and a roadmap to every Python guide.