Today we’ll be talking about two basic operations on lists: slicing and concatenation.
Here’s the video version of this article:
Lists are sequences, just like strings. We can perform similar operations on them:
Slicing
Lists can be sliced just like strings. Inside the square brackets you need to specify at least one index, then it’s the past index and the start index is then at its default value of 0. The past index is not included. You can also specify the step. If you want to learn more about string slicing, make sure to read this article. You can use everything you learn there with lists and other sequences.
>>> colors = ["brown", "yellow", "blue", "gray", "green"]
>>> my_favorite_colors = colors[1:3]
>>> print(my_favorite_colors)
['yellow', 'blue']
Concatenation
We can concatenate lists. It works exactly like with strings, so if you want to learn more about concatenation, you can read this article.
You can concatenate lists using literals:
>>> [1, 2, 3] + [12, 6]
[1, 2, 3, 12, 6]
or variables:
>>> german_cities = ["Munich", "Berlin"]
>>> spanish_cities = ["Madrid", "Barcelona", "Toledo"]
>>> italian_cities = ["Rome", "Naples"]
>>> european_cities = german_cities + spanish_cities + italian_cities
>>> print(european_cities)
['Munich', 'Berlin', 'Madrid', 'Barcelona', 'Toledo', 'Rome', 'Naples']
or both:
>>> european_cities + ["Paris", "Dublin", "Prague"]
['Munich', 'Berlin', 'Madrid', 'Barcelona', 'Toledo', 'Rome', 'Naples', 'Paris', 'Dublin', 'Prague']
For mutable sequences (like lists) you can use the augmented assignment operator (+=). The following two syntaxes give the same results:
a = a + b
a += b
but the one with the augmented assignment operator is more efficient because a is evaluated only once.
Here are some examples:
>>> numbers = [1, 3, 8]
>>> numbers = numbers + [7, 0]
>>> numbers
[1, 3, 8, 7, 0]
>>> numbers += [4, 10, 11] # same as numbers = numbers + [4, 10, 11]
>>> numbers
[1, 3, 8, 7, 0, 4, 10, 11]