Chapter 9. Lists

This chapter presents one of Python’s most useful built-in types, lists. You will also learn more about objects and what can happen when multiple variables refer to the same object.

In the exercises at the end of the chapter, we’ll make a word list and use it to search for special words like palindromes and anagrams.

A List Is a Sequence

Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements.

There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]). For example, here is a list of two integers:

numbers = [42, 123]
       

And here’s a list of three strings:

cheeses = ['Cheddar', 'Edam', 'Gouda']
       

The elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and even another list:

t = ['spam', 2.0, 5, [10, 20]]
       

A list within another list is nested.

A list that contains no elements is called an empty list; you can create one with empty brackets, []:

empty = []
       

The len function returns the length of a list:

len(cheeses)
       
3
       

The length of an empty list is 0.

The following figure shows the state diagram for cheeses, numbers, and empty:

Lists are represented by boxes with the word “list” outside and the numbered elements of the list inside.

Lists Are Mutable ...

Get Think Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.