/  Technology   /  How do I concatenate two lists in Python?
How do I concatenate two lists in Python

How do I concatenate two lists in Python?

 

In this article, let’s learn various ways to concatenate any two given lists. Let’s consider two lists named list_1 and list_2 with the following elements as an example while dealing with the methods.

Example:

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

 

Using for loop:

In this approach, we take an iterator ‘i’ in the loop to iterate through list_2 and add each element of it to the first list using the append() list method.

Example:

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

for i in list_2 :
   list_1.append(i)

print ("Concatenated list: " +str(list_1))

Output:

 

Using ‘+’ operator:

This is the most conventional way to concatenate two lists. The ‘+’ operator simply adds the complete second list at the end of the first list.

Example:

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

list_1 = list_1 + list_2

print ("Concatenated list: " + str(list_1))

Output:

 

Using List Comprehension:

Refer to this article to learn more about List comprehension

In this approach, a new list result is created in which the concatenated list is stored. This is a one-liner code that can be used as an alternative to the above loop method.

Example:

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

result = [j for i in [list_1, list_2] for j in i]

print ("Concatenated list using list comprehension: "+ str(result))

Output:

 

 

Using extend():

In this approach, we pass the list which is to be added, as an argument to the extend() method. 

Example:

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

list_1.extend(list_2)

print ("Concatenated list: "+ str(list_1))

Output:

 

Using * operator:

In this approach, a new list result is created to store the concatenated list. Here we can concatenate more than two lists. We can use this method only in versions Python 3.6 and above.

Example:

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

result = [*list_1, *list_2]

print ("Concatenated list: "+ str(result))

Output:

 

Using itertools.chain():

We import the itertools library to implement this approach. This library has various functions. These functions can be used to manage iterators which iterate through the iterables like lists and strings easily. These itertools treat consecutive sequences as a single sequence by iterating through the iterable which is passed as an argument in a sequential manner. The general syntax is 

list( itertools.chain (*iterable))

Example:

import itertools

list_1 = [1,3,5,7,9]
list_2 = [2,4,6,8,10]

result = list(itertools.chain(list_1, list_2))

print ("Concatenated list: " + str(result))

Output:

 

Leave a comment