Chapter 12. Collecting Things Together—Lists

 

We’ve seen that Python can store things in its memory and retrieve them, using names. So far, we have stored strings and numbers (both integers and floats). Sometimes it’s useful to store a bunch of things together in a kind of “group” or “collection.” Then you can do things to the whole collection at once and keep track of groups of things more easily. One of the kinds of collections is a list. In this chapter, we’re going to learn about lists—what they are and how to create, modify, and use them.

Lists are very useful, and they’re used in many, many programs. We’ll use a lot of them in the examples in upcoming chapters when we start doing graphics and game programming, because the many graphical objects in a game are often stored in a list.

What’s a list?

If I asked you to make a list of the members of your family, you might write something like this:

In Python, you’d write this:

family = ['Mom', 'Dad', 'Junior', 'Baby']

If I asked you to write down your lucky numbers, you might write this:

In Python, you’d write this:

luckyNumbers = [2, 7, 14, 26, 30]

Both family and luckyNumbers are examples of Python lists, and the individual things inside lists are called items. As you can see, lists in Python aren’t much different from lists you make in everyday life. Lists use square brackets to show where the list starts and ends, and they use commas to separate the items inside.

Creating a list

Adding things to a list

What’s the dot?

Lists can hold anything

Getting items from a list

“Slicing” a list

Modifying items

Other ways of adding to a list

Deleting from a list

Searching a list

Looping through a list

Sorting lists

Mutable and immutable

Lists of lists: tables of data

What did you learn?

Test your knowledge

Try it out