Course 1.2Lesson 4 of 5
Python has four containers for many values. A list keeps an order, can change, and allows repeats. A tuple keeps an order, cannot change, and allows repeats. A set has no order, allows no repeats, and gives a fast yes or no test. A dictionary finds a value by its key, and the keys are unique. To choose, ask three questions: do I need an order or a position, do I need to change it, and do I look things up by a name. You can change one container into another with list, tuple, set and dict, and with items.
Try the code and the simulations beside the lesson.
After this lesson you can
You now know all four ways in which Python keeps many values together.
| List | Tuple | Set | Dictionary | |
|---|---|---|---|---|
| Written with | [1, 2] | (1, 2) | {1, 2} | {"a": 1} |
| Order | yes | yes | no | order of adding |
| Can change | yes | no | yes | yes |
| Repeats | allowed | allowed | no | keys are unique |
| Find by | position | position | membership | key |
| Typical use | a sequence that grows | a fixed record | different values, overlap | a lookup table |
Predict first, then run it. Each container answers one kind of question best.
(3, 4) is a fixed pair: x and y.At the end, the program changes one container into another.
list(seen) is a list in no particular order. sorted(seen) is a list in order.tuple(marks_list) freezes a list.set(marks_list) drops the repeats.list(marks_dict.items()) gives a list of (key, value) tuples. And dict(that_list) goes back the other way.Some examples.
| The job | The container | Why |
|---|---|---|
| the marks of a class, in the order of the roll numbers | list | an order, and it grows |
| the (latitude, longitude) of a city | tuple | two values that belong together |
| the different cities that you visited | set | each once, and you ask "did I go there?" |
| the population of each city | dictionary | found by the name of the city |
| the words of a sentence, to count them | list, then a dictionary | split gives a list, counting needs a dictionary |
For a handful of items the difference does not matter. For thousands of lookups in a big collection, a set wins.
For a big collection, x in a_set and d[key] are fast. x in a_list is slow, because Python looks at the items one by one. If you test membership many times, a set is the better tool.
set(a_list) loses the repeats and the order.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
list(), tuple(), set() and dict() change one container into another.in and a dictionary lookup are fast for sets and dictionaries.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.