Merge / Join Two or More Python List for Beginners – Python Tutorial

By | July 9, 2019

Merge / Join python lists is very common to use in python applications, which can simpfy the process of python lists. In this tutorial, we will introduce how to merge or join them.

python join list

Method 1: Use + operation

Create two python lists

>>> list_1 = ['this', 'is', 'my', 'site']
>>> list_2 = [100, 1001]

Merge two lists

>>> list_3 = list_1 + list_2
>>> list_3

The output is:

['this', 'is', 'my', 'site', 100, 1001]

Method 2: Use list.extend() function

>>>list_1.extend(list_2)
>>>list_1

The output is:

['this', 'is', 'my', 'site', 100, 1001]

Notice: list_1.extend() function does not return a list, this function extend elements of list_1 with list_2.

Method 3: Use itertools.chain() function

Preliminaries

>>> from itertools import chain

Create two python lists

>>> list_1 = ['this', 'is', 'my', 'site']
>>> list_2 = [100, 1001]

Chain two lists

>>> list_3 = chain(list_1, list_2)
>>> for i in list_3:
...     print i
...

The output is:

this
is
my
site
100
1001

Notice: chain() function return a generator object with python yield statement.

Leave a Reply

Your email address will not be published. Required fields are marked *