/  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.

 

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.

 

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.

 

Using List Comprehension:

Refer to this article to learn more about list comprehension

https://www.i2tutorials.com/list-comprehensions/

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.

 

 

Using extend():

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

 

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.

 

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))

Leave a comment