Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k 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 (106k 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)

   image

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

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

Related questions

+2 votes
3 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...