Python Lists, Dicts, and Sets — The Three Collections You Use Every Day
A list keeps values in order. A dict finds a value by its key. A set keeps each value once and answers whether a value is present. This guide runs small programs, one per collection: a list of scores reports max 95 and sorts to [79, 88, 92, 95], a dict of ages gains a key and answers a missing key two different ways, and a set built from four tags reports unique tags 3 because one tag was written twice. The guide also shows the two mistakes beginners make with these types: reading a missing dict key with square brackets, which raises KeyError, and treating sorted and sort as the same operation, which they are not.
Written November 11, 2026 · Tested with Python 3.12.3 · 9 min read
- The main program: one of each
- Lists: order, indexing, slicing, and append
- sorted returns a new list, sort changes the list in place
- List comprehensions: a list built in one expression
Written November 11, 2026
Tested with Python 3.12.3
What this guide is
Python has three collection types that cover most everyday work. A list holds values in a fixed order, and each value sits at a numbered position. A dict holds pairs of a key and a value, and finds a value when given its key. A set holds values with no duplicates and no order, and answers one question well: is this value present. This guide runs one main program that uses all three, and then runs a short program per rule: indexing and slicing a list, the difference between sorted and sort, a missing dict key read two ways, and a set built from words with repeats.
The main program: one of each
scores = [88, 92, 79, 95]
print("max", max(scores), "sorted", sorted(scores))
squares = [n * n for n in range(5)]
print("squares", squares)
ages = {"ana": 30, "bo": 25}
ages["cy"] = 40
print("ana", ages.get("ana"), "missing", ages.get("zoe", "unknown"))
print("keys", sorted(ages.keys()))
tags = {"cpp", "go", "rust", "cpp"}
print("unique tags", len(tags), "has go:", "go" in tags)
The exact output:
max 95 sorted [79, 88, 92, 95]
squares [0, 1, 4, 9, 16]
ana 30 missing unknown
keys ['ana', 'bo', 'cy']
unique tags 3 has go: True
Each line is one collection doing its job. The list reports its largest value and a sorted copy of itself. The comprehension builds a second list of squares. The dict gains a third entry, answers a present key with its value, and answers a missing key with the default the caller supplied. The set was written with four values and holds three, because cpp appears twice and a set keeps each value once. The sections below take each type in turn.
Lists: order, indexing, slicing, and append
A list keeps the order its values were written in, and each position has an index that starts at 0. A second program reads the same scores list three ways and then grows it:
scores = [88, 92, 79, 95]
print("first", scores[0], "last", scores[-1], "slice", scores[1:3])
scores.append(100)
print("after append", scores, "len", len(scores))
The exact output:
first 88 last 95 slice [92, 79]
after append [88, 92, 79, 95, 100] len 5
The index 0 reads the first value, and the index -1 reads the last one. The slice scores[1:3] returns a new list with the values at positions 1 and 2, in the original order: the start index is included and the end index is not. The method append adds one value at the end, and the length grows from 4 to 5. A list is the right collection when order matters and when the program needs to read values by position: a queue of jobs, the lines of a file, the results of a search.
sorted returns a new list, sort changes the list in place
Python has two ways to sort a list, and they differ in what they return. The function sorted builds a new list and leaves the original alone. The method sort reorders the list it is called on and returns None. A third program shows both:
nums = [3, 1, 2]
new = sorted(nums)
print("sorted returns", new, "original", nums)
nums.sort()
print("after sort", nums, "sort returns", nums.sort())
The exact output:
sorted returns [1, 2, 3] original [3, 1, 2]
after sort [1, 2, 3] sort returns None
The first line is the whole lesson: after sorted(nums), the new list is [1, 2, 3] and the original is still [3, 1, 2]. The second line shows the trap form: nums.sort() did reorder nums, and the value it returned is None, so code that writes nums = nums.sort() replaces the list with None and loses the data. Use sorted when the original order is still needed, and use sort when the list itself should end up sorted and nothing needs the return value.
List comprehensions: a list built in one expression
The main program builds its second list with a comprehension: [n * n for n in range(5)]. A comprehension reads as the loop it replaces: for each value n in range(5), compute n * n and collect the results into a new list. The output is squares [0, 1, 4, 9, 16], the squares of 0 through 4 in order. The comprehension form wins when the job is a plain transform or filter of an existing sequence, because the result is a list by construction and there is no separate accumulator variable to initialize or append to. A plain loop still wins when the body does several things at once, or when the steps need names of their own to stay readable. The rule of thumb used in practice: one expression per element is a comprehension, several statements per element is a loop.
Dicts: values found by key, and get with a default
A dict stores a value under a key, and reads it back by the same key. In the main program, ages starts as {"ana": 30, "bo": 25} and the assignment ages["cy"] = 40 adds a third pair, which is why the sorted keys print as ['ana', 'bo', 'cy']. The read that matters is the one for a key that is not there. The program uses the method get twice in effect: ages.get("ana") returns 30 because the key is present, and ages.get("zoe", "unknown") returns the string unknown because the key is absent and a default was supplied. A fourth program isolates the two get forms:
ages = {"ana": 30}
print("get missing:", ages.get("zoe"))
print("get default:", ages.get("zoe", "unknown"))
The exact output:
get missing: None
get default: unknown
Without a default, get returns None for a missing key. With a default, it returns the default. Either way, the program keeps running, which is the contrast with the square-bracket read in the trap section below. Use get whenever a missing key is a normal possibility, and pass a default that fits the caller: a count that starts at 0, a list that starts empty, a label such as unknown.
Sets: duplicates dropped, membership in one test
A set keeps each value once. The main program writes {"cpp", "go", "rust", "cpp"} and the length is 3, because the second cpp adds nothing. A fifth program builds a set from a list with repeats:
words = ["bo", "ana", "bo", "cy", "ana"]
print("deduped", sorted(set(words)), "count", len(set(words)))
The exact output:
deduped ['ana', 'bo', 'cy'] count 3
Five words go in and three come out. Converting a list to a set is the standard one-line way to drop duplicates; converting back with sorted returns the unique values in a stable order. The membership test is the other half of the set's job: "go" in tags in the main program prints True, and the same in test on a list would scan the list from the start, while a set answers from its hash table. A set also has no indexing, as the second trap below shows.
Trap: reading a missing dict key with square brackets
get read look alike and behave oppositely for a missing key. This program reads a key that is not in the dict:ages = {"ana": 30}
print(ages["zoe"])
It does not print anything. It fails, and the run exits with code 1 and this error:
Traceback (most recent call last):
File "keyerror.py", line 2, in <module>
print(ages["zoe"])
~~~~^^^^^^^
KeyError: 'zoe'
The last line names the problem: KeyError: 'zoe'. The bracket read is the right choice when the key must be present and a missing key means the program itself is wrong, because the failure is loud and immediate. It is the wrong choice when a missing key is ordinary input, because every absent key becomes a crash. The get forms in the dict section are the fix for that case. A second, smaller trap of the same shape: a set has no positions, so tags[0] fails with TypeError: 'set' object is not subscriptable. If a program needs the first value, it needs a list, not a set.
Which collection for which job
| Job | Collection | Why |
|---|---|---|
| Values in order, read by position, grown at the end | list | Indexing, slicing, and append, as the scores programs show |
| A value looked up by a name or an ID | dict | The key finds the value, and get handles a missing key |
| Duplicates removed, or a fast is-it-present test | set | Each value is kept once, and in answers membership |
| Unique values in a stable, readable order | list built from sorted(set(...)) |
The set removes duplicates, and sorted restores order |
The deciding question is how the program reaches the values. By position means a list. By key means a dict. By presence alone means a set. Most programs use all three in different places, the way the main program does: a list for the scores, a dict for the ages, a set for the tags.
Checklist
- Before reading a value by position, use a list: index 0 is the first value, and index -1 is the last.
- Before sorting, decide which form fits:
sortedreturns a new list, andsortchanges the list and returnsNone. - Before building a list with a loop that only transforms each element, consider a comprehension: one expression per element, collected in order.
- Before reading a dict key that might be missing, use
getwith a default that fits the caller: the bracket read raisesKeyError. - Before storing values that must stay unique, use a set: duplicates are dropped on entry, and
intests membership. - Before relying on the order of a set, sort it: a set keeps no order, and its iteration order differs between runs.
Related guides on this site
- Go Slices and Maps — Append, Length, Capacity, and Lookup — the parallel foundation guide in the Go series, where a slice grows with append and a map answers with the comma-ok idiom.
- Taking a Real Codebase to mypy --strict — the advanced Python guide on this site, taking a real codebase to strict typing.
- Migrating to a uv Workspace: The Traps, in the Order They Bite — the Python tooling guide on this site, on moving a project to a uv workspace.
Sources
- Python Tutorial, Data Structures — lists, list comprehensions, and the methods and operations for the built-in collection types.
- Python Tutorial, Dictionaries — dict construction, key lookup, and the
getmethod. - Python Tutorial, Sets — set construction, duplicate removal, and membership testing.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.