How can I get the concatenation of two lists in Python without modifying either one? [duplicate]
Asked Answered
D

7

709

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?

Difficult answered 3/12, 2010 at 9:16 Comment(0)
C
1151

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

Coachman answered 3/12, 2010 at 9:17 Comment(4)
Actually you can do this by using the a non hidden function: import operator, operator.add(list1, list2)Cupule
reduce(operator.add, [[1,2], [3,4], [5,6]]) == [1,2,3,4,5,6]. Or you can use itertools.chain instead of operator.addImprovised
you can also use numpy.concatenate((a,b),axis=0)Sexlimited
You can also use list1.extend(list2)Orford
I
174

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.

Ionize answered 3/12, 2010 at 10:41 Comment(1)
just say that itertools.chain returns a generator...Nathanielnathanil
N
117

concatenated_list = list_1 + list_2

Nauseating answered 3/12, 2010 at 9:18 Comment(0)
B
102

You can also use sum, if you give it a start argument:

>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

This works in general for anything that has the + operator:

>>> sum([(1,2), (1,), ()], ())
(1, 2, 1)

>>> sum([Counter('123'), Counter('234'), Counter('345')], Counter())
Counter({'1':1, '2':2, '3':3, '4':2, '5':1})

>>> sum([True, True, False], False)
2

With the notable exception of strings:

>>> sum(['123', '345', '567'], '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Berryberryhill answered 12/2, 2014 at 13:6 Comment(1)
On Python 3.5.2, sum is documented to say "This function is intended specifically for use with numeric values and may reject non-numeric types". So I'm not sure sum should be used like this.Macario
T
45

you could always create a new list which is a result of adding two lists.

>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]

Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.

Tetracycline answered 3/12, 2010 at 9:18 Comment(1)
It only makes sense to modify the original lists if you don't need the unmodified lists any more, so in this case it wouldn't make sense.Ionize
P
24

And if you have more than two lists to concatenate:

import operator
from functools import reduce  # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

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.

Particulate answered 27/8, 2013 at 8:41 Comment(0)
N
16

Just to let you know:

When you write list1 + list2, you are calling the __add__ method of list1, which returns a new list. in this way you can also deal with myobject + list1 by adding the __add__ method to your personal class.

Nathanielnathanil answered 3/12, 2010 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.