# How can I get the concatenation of two lists in Python without modifying either one?

1 view
in Python

In Python, the only way I can find to concatenate two lists is list.extend, which modifies the first list. Is there any concatenation function that returns its result without modifying its arguments?

by (107k points)
edited by
• The simplest way for concatenating a list is to use  ‘list1+list2’. This gives a new list that is the concatenation of list1 and list2.

a = [1, 2, 3]

b = [4, 5, 6]

print(a+b)

• Another thing you can use itertools.chain() method:-

• itertools.chain():-

It make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Basically it is used for treating consecutive sequences as a single sequence.

import itertools

a = [1, 2, 3]

b = [4, 5, 6]

c = itertools.chain(a, b)

for i in c:

print i

• This method creates a generator for the items in the combined list, which has the advantage that no new list needs to be created.

• This method becomes very handy if your lists are large and efficiency is a concern.