How can I get the concatenation of two lists in Python without modifying either one?
Yes: list1 + list2
. This gives a new list that is the concatenation of list1
and list2
.
The simplest method is just to use the +
operator, which returns the concatenation of the lists:
concat = first_list + second_list
One disadvantage of this method is that twice the memory is now being used . For very large lists, 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
1
2
3
4
5
6
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.
concatenated_list = list_1 + list_2