chapter three

3 Lists and tuples

 

Consider a program that has to work with documents. Or keep track of users. Or log the IP addresses that have accessed our server. Or store the names and birthdates 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 a number of "collections," data structures that 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 list of documents, users, or IP addresses would be best stored in lists — because we have many objects of the same type. A record containing one person’s name and birthdate would be best stored in a tuple, because the name and birthdate are of different types. A bunch of such name-birthday tuples, however, could be stored in a list, because it contains a sequence of tuples — and the tuples are all of the same type.

3.1  First-last

3.1.1  Solution

3.1.2  Discussion

3.1.3  Beyond the exercise

3.2  All A’s

3.2.1  Solution

3.2.2  Discussion

3.2.3  Beyond the exercise

3.3  Summing anything

3.3.1  Solution

3.3.2  Discussion

3.3.3  Beyond the exercise

3.4  Alphabetizing names

3.4.1  Solution

3.4.2  Discussion

3.4.3  Beyond the exercise

3.5  Word with most repeated letters

3.5.1  Solution

3.5.2  Discussion

3.5.3  Beyond the exercise

3.6  Printing tuple records

3.6.1  Solution

3.6.2  Discussion