O'Reilly logo

Raspberry Pi Cookbook, 2nd Edition by Simon Monk

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 using [ and ] 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 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required