List vs Tuple vs Set vs Dictionary in Python
List vs Tuple vs Set vs Dictionary
A collection is one value that holds many values. Python has four of them: the list, the tuple, the set and the dictionary. Each one is best at a different job.
Think of a school. The lunch queue is a list: it has an order, and people join and leave. A student's date of birth is a tuple: fixed values that never change. The clubs a student has joined are a set: each club once, in no special order. The register from roll number to name is a dictionary: you look a name up by its number.
The four side by side
| List | Tuple | Set | Dictionary | |
|---|---|---|---|---|
| Written as | [1, 2] | (1, 2) | {1, 2} | {"a": 1} |
| Keeps the order | yes | yes | no | yes |
| Can change | yes | no | yes | yes |
| Duplicates | allowed | allowed | dropped | keys: never |
| Read one item | by index: x[0] | by index: x[0] | no, ask with in | by key: x["a"] |
| Empty | [] | () | set() | {} |
| Chapter | 9 | 14 | 14 | 13 |
queue = ["Sunny", "Rocky", "Sunny"]
birthday = (12, 5, 2001)
clubs = {"chess", "music", "chess"}
ages = {"Sunny": 25, "Rocky": 23}
print(len(queue), len(birthday), len(clubs), len(ages))3 3 2 2
The list kept both Sunnys, the set dropped the second "chess", and the dictionary counts its keys.
What they share
len()works on all four.inworks on all four. On a dictionary, it checks the keys.- A for loop works on all four. On a dictionary, it goes through the keys; on a set, in the set's own order.
Common beginner doubt
"Which one is the best?" None of them! The list is the everyday choice, and you'll use it most. The other three are for special jobs: a tuple when the values must stay fixed, a set when every item must be unique, and a dictionary when you look things up by a name. The next lesson turns this into four quick questions.
List: ordered and changeable. Tuple: ordered and fixed. Set: unique, no order. Dictionary: values found by key.