This question already has an answer here:
- How to concatenate two lists in Python? 30 answers
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?
Depending on how you're going to use it once it's created
itertools.chain
might be your best bet: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: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 uselist(c)
to create the full list, but that will create a new list in memory.concatenated_list = list_1 + list_2
Yes:
list1+list2
. This gives a new list that is the concatenation oflist1
andlist2
.And if you have more than two lists to concatenate:
It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g.,
*args
.You can also use
sum
, if you give it astart
argument:This works in general for anything that has the
+
operator:With the notable exception of strings:
you could always create a new list which is a result of adding two lists.
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.