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


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?

12/3/2010 9:16:30 AM

Accepted Answer

Yes: list1+list2. This gives a new list that is the concatenation of list1 and list2.

12/3/2010 10:56:27 AM

Depending on how you're going to use it once it's created itertools.chain might be your best bet:

>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)

This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use c as though it were the concatenation of the two lists:

>>> for i in c:
...     print i

If your lists are large and efficiency is a concern then this and other methods from the itertools module are very handy to know.

Note that this example uses up the items in c, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c) to create the full list, but that will create a new list in memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow