Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2.3 Collections

Variables containing single values like an integer or a string will only get you so far. Many real-world applications for example require you to store a whole collection of values in a single data structure. Here, the most important and widely used solutions from the Python standard library are lists, tuples, and dicts (dictionaries).

Lists

Lists are the most common collection in Python. They are a heterogeneous collection of objects, which means they are not limited to elements of a single type but can also contain multiple types if this is required. Lists are initialized with square brackets [] and their elements are separated through commas:

Indexing

Lists are ordered collections, which means that the order of items is important and will not change (unless we specifically change it). This allows us to access individual elements of the list by specifying their position, which is also called an index. The process of accessing individual or multiple values from a data structure is analogously called indexing.

To access the ith element in a list, we enclose the desired index i in square brackets. Note that Python, unlike for example MATLAB, uses zero-based indexing. This means the first element of a collection is at index 0, while index 1 returns the second element (and so forth).

'apple'
3.14

Slicing

What if you want to retrieve more than a single element from a list? For this we can use slicing operations, which use the colon (:) operator:

[3.14, True]

The colon is used to separate a starting and a stopping index. Intuitively you can read this notation as “from random_stuff get items 1 to 3”. Note that the starting position is inclusive (meaning it includes the item at position 1, which in this case is 3.14) while the stopping index is exclusive (meaning that the item at position 3, which here would be 4, is not included). If you are interested in some arguments for that logic, you can refer to this 1982 “article” from Edsger Dijkstra.

Modifying lists

Lists are mutable objects, which means they can be modified after they have been created. For example, we can replace a specific element with another element:

Before re-assignment: ['apple', 3.14, True, 4]
After re-assignment: ['banana', 3.14, True, 4]

Another common use case is to add new values to a list (for example once new results have been calculated). This can be done by using the .append() function on the list:

['banana', 3.14, True, 4, 'goodbye']

There are many more things you can do to lists, like removing items or sorting the list. You can read up on these methods e.g. here.

Tuples

Tuples are similar to lists in that they are an ordered collection of elements. However, they are immutable in nature, meaning you can not change their content after creating them. For creating tuples, you simply use the round brackets instead of the square ones:

Tuples only have two built-in methods which are .count() and .index():

The first occurrence of 2 is at index: 2.
The number 2 appears 2 times in the tuple.

In case you still need a mutable version of the tuple, you can convert any tuple to a list by using the list() function:

Dictionaries

Dictionaries (dicts) are another popular data structure in Python. In short, dicts are mappings from keys to values. You can think of them as key-value pairs, where keys within a single dictionary need to be unique, while the values do not. Most programming languages have similar structures, for example maps in MATLAB.

Dictionaries are created by using curly brackets, and can either be initialized as empty or with key-value pairs separated by commas:

As you can see, dicts are quite versatile. Keys are required to be immutable like a string, number, or tuple (this is so they do not unexpectedly change during your program and make things really messy). The values, however, can be of any type you want!

Accessing values stored in a dictionary is slightly different. While you previously accessed items in lists by their position, values in a dictionary are accessed by their key (dictionaries do remember the order in which items were inserted, but you cannot use positions to index them). The syntax is identical to that used for list indexing, we simply specify the key between square brackets:

'Alice'

Dictionaries can be updated or, if the key does not exist yet, extended through the same []-based syntax, except you now have to make an assignment using the (=) operator:

{'name': 'Alice', 'age': 27, 1: 'integer_key', (1, 2): 'tuple_key', 'list_value': [0.5, 0.3]}