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?
list1+list2. This gives a new list that is the concatenation of
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.