Lists in Python
With variables, we got to know the possibility of storing content in a placeholder (i.e. the variable). However, each variable can only have one value.
firstname1 = 'Jean' firstname2 = 'Alex' firstname3 = 'Emily'
But what if we would like to store multiple values? That’s why there are so-called “lists” in Python. If you already know another programming language, this option is called an array.
How can we store content in lists in Python? Quite simply using the square brackets:
firstname = ['Jean', 'Alex', 'Emily']
The output can be done as usual via print():
firstname = ['Jean', 'Alex', 'Emily'] print(firstname)
All first names are now displayed. If we only want to output a certain first name, we have to include the index number. This is written in square brackets.
firstname = ['Jean', 'Alex', 'Emily'] print(firstname[1])
Output:
Alex
Why not the first element of our list, which obviously contains “Jean”? Here, it’s important that computers always start counting from 0, especially with lists. So if we want to get the first element of our first name list, we have to enter 0 as index:
firstname = ['Jean', 'Alex', 'Emily'] print(firstname[0])
Now we get the first element of the list. Hence the important reminder
Get the last element of the list
We can also start from the back. And here you start with -1! So we output the last element with:
firstname = ['Jean', 'Alex', 'Emily'] print(firstname[-1])
Output:
Emily
Overwrite list values
If we want to overwrite an existing list entry because Alex has become Alexa, we can do this using the index number and a new value assignment:
firstname = ['Jean', 'Alex', 'Emily'] firstname[1] = "Alexa"
Let’s now output our list with print():
firstname = ['Jean', 'Alex', 'Emily'] firstname[1] = "Alexa" print(firstname)
So the list comes with the changed value:
['Jean', 'Alexa', 'Emily']
Extend lists with additional elements
We can easily expand Python lists using the plus sign (+).
firstname = ['Jean', 'Alex', 'Emily'] firstname += ['Yohan', 'Bob']
The existing list will now be expanded to include these 2 elements. If we print the list, we get:
['Jean', 'Alexa', 'Emily', 'Yohan', 'Bob']
This firstname += ['Yohan', 'Bob']
means firstname = firstname + ['Yohan', 'Bob']
Python provides various functions for lists. There is a function for expanding lists: listname.append('new value')
. As a concrete example it looks like this:
firstname = ['Jean', 'Alex', 'Emily'] firstname.append('Bob')