3 Lists and tuples

 

Consider a program that has to work with documents, keep track of users, log the IP addresses that have accessed a server, or store the names and birth dates of children in a school. In all of these cases, we’re storing many pieces of information. We’ll want to display, search through, extend, and modify this information.

These are such common tasks that every programming language supports collections, data structures designed for handling such cases. Lists and tuples are Python’s built-in collections. Technically, they differ in that lists are mutable, whereas tuples are immutable. But in practice, lists are meant to be used for sequences of the same type, whereas tuples are meant for sequences of different types.

For example, a series of documents, users, or IP addresses would be best stored in a list—​because we have many objects of the same type. A record containing someone’s name and birth date would be best stored in a tuple, because the name and birth date are of different types. A bunch of such name-birth date tuples, however, could be stored in a list, because it would contain a sequence of tuples—​and the tuples all would be of the same type.

3.1 Useful references

3.2 Exercise 9 ■ First-last

3.2.1 Working it out

3.2.2 Solution

3.2.3 Beyond the exercise

3.3 Exercise 10 ■ Summing anything

3.3.1 Working it out

3.3.2 Solution

3.3.3 Beyond the exercise

3.4 Exercise 11 ■ Alphabetizing countries

3.4.1 Working it out

3.4.2 Solution

3.4.3 Beyond the exercise

3.5 Exercise 12 ■ Word with most repeated letters

3.5.1 Working it out

3.5.2 Solution

3.5.3 Beyond the exercise

3.6 Exercise 13 ■ Printing tuple records

3.6.1 Working it out

3.6.2 Solution

3.6.3 Beyond the exercise

3.7 Summary