Tuples
A tuple is a sequence that cannot change
Round brackets. Read like a list. Immutable.
A tuple looks like a list written with round brackets. It has the same indexes, from zero, and from minus one at the far end. Reading works the same way: t zero is ten, t minus one is thirty, and a slice gives a new tuple. The difference is that nothing can be changed. Assigning to an index is a type error.
Tuples · Going deeper
Writing a tuple
(5,) is a tuple. (5) is an int.
Tuples and lists
The tuple is fixed. A list inside it is not.
Cannot replace an item. Can change a mutable item.
Tuples and lists can be nested in each other. This tuple has two items: the number one, and a list. The second item is a reference to that list. The tuple cannot be given a different second item. But the list it points at is still a list, so appending to it works. The tuple now shows one, then two, three, four.
Tuples and lists · Going deeper
List or tuple
Mutable or immutable.
Check yourself
What does this print?
Sets
A set keeps one of each value, in no order
Unique values. No index. add() and remove().
A set is a collection built for one job: knowing whether a value is present. Write five values, two of them repeated, and the set holds three. Add puts a new value in. Adding a value that is already there does nothing at all. Remove takes a value out.
Sets · Going deeper
Set facts
set() is empty. {} is a dict.
Dictionaries
A dictionary finds a value by its key, not its position
key: value. d[key] reads, adds and replaces.
A dictionary stores pairs: a key, and the value that belongs to it. Here the keys are names and the values are ages. Assign to a key that is not there, and a new pair is added. Assign to a key that is there, and its value is replaced. Del removes a pair by its key.
Dictionaries · Going deeper
Dictionary facts
in tests keys. Missing key: KeyError.
Check yourself
What does this print?
Dictionary methods
Looping over a dictionary gives its keys
keys(), values(), items().
Three methods let you go through a dictionary. Keys gives the keys. Values gives the values. Items gives each pair, as a tuple of two. That is what makes this loop work: each pair is unpacked into k and v. A plain for k in d gives you the keys.
Dictionary methods · Going deeper
Five collections compared
list, tuple, set, dict, str.
Check yourself
What does this print?
Lesson complete
You finished “Tuples, sets and dictionaries”
Answer the questions along the way to see your score here.