Python: Concatenating lists with the unpack operator

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.

Concatenating two lists in Python with the "+" operator.
Figure 1 – Concatenating two lists in Python with the “+” operator.

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.

Concatenating two lists with the "*" operator.
Figure 2 – Concatenating two lists with the “*” operator.

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.

Error obtaining when concatenating different iterables.
Figure 3 – Error obtaining when concatenating different iterables.

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.

Output of merging the three iterables with the "*" operator.
Figure 4 – Output of merging the three iterables with the “*” operator.

Leave a Reply