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.

Exercise 9 First-last

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 10 Summing anything

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 11 Alphabetizing names

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 12 Word with most repeated letters

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 13 Printing tuple records

Working it out

Solution

Screencast solution

Beyond the exercise