Chapter 11. Data Structures in Python

In Chapter 10, you learned about simple Python object types like strings, integers, and Booleans. Now let’s look at grouping multiple values together in what’s called a collection. Python by default comes with several collection object types. We’ll start this chapter with the list. We can put values into a list by separating each entry with commas and placing the results inside square brackets:

In [1]: my_list = [4, 1, 5, 2]

Out[1]: [4, 1, 5, 2]

This object contains all integers, but itself is not an integer data type: it is a list.

In [2]: type(my_list)

Out[2]: list

In fact, we can include all different sorts of data inside a list…even other lists.

In [3]: my_nested_list = [1, 2, 3, ['Boo!', True]]

Out[3]: list

As you’re seeing, lists are quite versatile for storing data. But right now, we’re really interested in working with something that could function like an Excel range or R vector, and then move into tabular data. Does a simple list fit the bill? Let’s give it a whirl by trying to multiply my_list by two.

In [4]:  my_list * 2

Out[4]: [4, 1, 5, 2, 4, 1, 5, 2]

This is probably not what you are looking for: Python took ...

Get Advancing into Analytics now with O’Reilly online learning.

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