Data structures and containers
In the last section, we talked about variable types that store single values. Now we will move on to data structures that can hold multiple values. These data structures are lists, tuples, dictionaries, and sets. Lists and tuples are commonly referred to as sequences in Python. In this book, we will use the terms data structures and data containers interchangeably.
Lists
Lists are a widely used data structure that can hold multiple values. Let's look at some features of lists:
- To make a list, we use square brackets,
[]
. Example:my_list = [1, 2, 3]
. - Lists can hold any combination of numeric types, strings, Boolean types, tuples, dictionaries, or even other lists.
Example:
my_diverse_list = [51, 'Health', True, [1, 2, 3]]
. - Lists, like strings, are sequences and support indexing and slicing.
For example, in the preceding example,
my_diverse_list[0]
would equal51
.my_diverse_list[0:2]
would equal[51, 'Health']
. To access the3
of the nested list, we can usemy_diverse_list...