Concatenate lists in Python

When manipulating the lists, Python offers us multiple options. So, in this example, we are going to see how we can concatenate lists in Python.

To concatenate lists in Python we have two ways. On the one hand it will be using the sum operator and on the other it will be relying on the
.extend()
.

Create a list in Python

But let’s go step by step. The first thing will be to create a list, specifically what we will do is declare the two lists using Python code. To do this, we create and instantiate them directly with a series of values:

list1 = [1,2,3,4]
list2 = [5,6,7,8]

You must remember that the elements of a list in Python are enclosed in square brackets and separated by commas. In this case we are using lists of integers.

Concatenate lists in Python with sum operator

In this first case we are going to use the sum operator to concatenate lists in Python. To do this we will simply have to add the first list with the second using the + operator.

We are going to use the addition operator together with the assignment operator so that the result is in list1

list1+=list2
print "With + operator"
print list1

Specifically we have created a quick assignment using the += operator. And we will have the concatenated lists.

Concatenate lists in Python with .extend() method

The second case will use the method
.extend()
offered by the class
list
from Python. If we check the syntax of the
.extend()
we will see that we can add another iterable element to the list.

list.extend(iterable)

It is important to know that the
.extend()
is applied to the list in which it is instantiated. That is, it does not return a new list but rather modifies the source list.

Therefore, we will use the
.extend()
on the first list, using the second as a method parameter.

list1.extend(list2)
print "With .extend() method"
print list1

The
.extend()
has another abbreviated form that would be the following:

list[len(list):] = iterable

So we can also write our code as follows

list1[len(list1):] = list2
print "Shortcut"
print list1

We have already seen three simple ways to concatenate lists in Python.

Leave a Comment