0 votes
1 view
in Python by (47.8k points)

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?

1 Answer

0 votes
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]



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

To know more about this you can have a look at the following video tutorial:-

Related questions

+2 votes
3 answers
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !