The objective of this post is to check how to concatenate two lists in Python with the unpack operator “*”.
In python, there are multiple ways of merging two lists. One of the simplest is to use the “+” operator, like shown below.
x = [1,2,3] y = [4,5] print(x+y)
With this approach, the two lists are merged, as can be seen in figure 1.
An alternative way of doing this is by using the * operator. With this approach, we simply unpack the elements of each list into a new list.
x = [1,2,3] y = [4,5] print("Using the * operator") print([*x, *y])
The result will be the same as before, as indicated in figure 2.
Naturally both approaches are valid. Nonetheless, using the unpack operator has an advantage: the data structures can be different as long as they are iterable.
So, if we try to use the “+” operator to merge a list with a range or a tuple, it won’t work.
x = [1,2,3] y = range(4,5) z = (6,7) print(x+y+z)
If we try the previous code, we will obtain the result shown in figure 3.
If we use the “*” operator instead, we will be able to merge the three data structures.
x = [1,2,3] y = range(4,5) z = (6,7) print([*x, *y, *z])
As can be seen in figure 4, the operation works and we obtain a list with the elements of the three iterables.