Skip to Content
Raspberry Pi Cookbook, 3rd Edition
book

Raspberry Pi Cookbook, 3rd Edition

by Simon Monk
October 2019
Beginner to intermediate
608 pages
11h 41m
English
O'Reilly Media, Inc.
Content preview from Raspberry Pi Cookbook, 3rd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Raspberry Pi Cookbook, 4th Edition

Raspberry Pi Cookbook, 4th Edition

Simon Monk
Arduino Cookbook, 3rd Edition

Arduino Cookbook, 3rd Edition

Michael Margolis, Brian Jepson, Nicholas Robert Weldin

Publisher Resources

ISBN: 9781492043218Errata PageSupplemental Content