Chapter 6. Python Lists and Dictionaries

6.0. Introduction

In Chapter 5, we looked at the basics of the Python language. In this chapter, we look at two key Python data structures, lists and dictionaries.

6.1. Creating a List

Problem

You want to use a variable to hold a series of values rather than just one value.

Solution

Use a list. In Python, a list is a collection of values stored in order so that you can access them by position.

You create a list using [ and ] to contain its initial contents:

>>> a = [34, 'Fred', 12, False, 72.3]
>>>

Unlike more rigid arrays in languages like C, you don’t need to specify the size of a list in Python when you declare it. You can also change the number of elements in the list any time you like.

Discussion

As this example illustrates, the items in a list do not have to be all of the same type, although they often are.

If you want to create an empty list that you can add items to later, you can write:

>>> a = []
>>>

See Also

All the recipes between Recipes 6.1 and 6.11 involve the use of lists.

6.2. Accessing Elements of a List

Problem

You want to find individual elements of a list or change them.

Solution

Use the [] notation to access elements of a list by their position in the list. For example:

>>> a = [34, 'Fred', 12, False, 72.3]
>>> a[1]
'Fred'

Discussion

The list positions (indices) start at 0 for the first element.

As well as using the [] notation to read values out of a list, you can also use it to change values at a certain position. For example:

>>> a = [34 ...

Get Raspberry Pi Cookbook 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.