Chapter 6. Python Lists and Dictionaries

6.0 Introduction

In Chapter 5, you looked at the basics of the Python language. In this chapter, you 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 by using the [ and ] characters to contain its initial contents:

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

Unlike the 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 need to be all of the same type, although they often are.

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 (not at 1).

As well as using the [] notation to read values out of a list, you can also use ...

Get Raspberry Pi Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.