How to append list to second list

How do I concatenate two lists in Python?

Example:

listone = [1,2,3]
listtwo = [4,5,6]

Expected outcome:

joinedlist == [1, 2, 3, 4, 5, 6]
share improve this question
 
1 
what about if listone was [3,2,1]? Will the output change? –  barkmadley  Nov 12 '09 at 7:06
8 
Could have found answer in any Python reference or tutorial. Personally I don't mind, but this question looks like asked solely for reputation mining ;) –  Clergyman  Feb 8 '14 at 12:46
 
'merge' as 'create one shallow-copy', 'deep-copy' or 'iterate from'? (@Clergyman, it's not at all that trivial) –  smci  Sep 12 '14 at 3:31 
 
Isn’t this operation called concatination rather than merging? I always thought merging means concatination + sorting. –  mcb  Nov 8 '14 at 2:33 
 
This question's searchability could be improved if the terms 'looping' and 'concatenate' were added. –  florisla Sep 9 '15 at 13:22

17 Answers

up vote 1171 down vote accepted

Python makes this ridiculously easy.

mergedlist = listone + listtwo
share improve this answer
 
24 
does this create a deep copy of listone and appends listtwo? –  Daniel F  Apr 19 '12 at 12:34
53 
@Daniel it will create a new list with a shallow copy of the items in the first list, followed by a shallow copy of the items in the second list. Use copy.deepcopy to get deep copies of lists. –  Daniel G  Apr 19 '12 at 14:51
47 
another useful detail here: listone += listtwo results in listone == [1, 2, 3, 4, 5, 6] –  br1ckb0t  Jan 29 '14 at 16:14 
4 
@br1ckb0t will that change what listone is pointing at? So:list3 = listone  listone+=listtwo Is list3 changed as well? –  MikeH  Feb 19 '14 at 5:01 
3 
it does change list3. However, if that isn't a problem, it's simpler more readable to add the two lists instead of creating a new one. –  br1ckb0t  Feb 20 '14 at 18:55

It's also possible to create a generator that simply iterates over the items in both lists. This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

import itertools
for item in itertools.chain(listone, listtwo):
   # do something with each list item
share improve this answer
 
9 
This is better way because it also works with numpy array. –  d.putto  Sep 25 '12 at 9:37
1 
will this work the same way: mergedList = itertools.chain(listone, listtwo) for item in mergedList: –  yourfriendzak  Mar 1 '13 at 0:55 
4 
@d.putto: individual item access is very slow for numpy arrays (each access requires to convert the raw memory with a C type to Python object. Vectorized operations such as np.dot() work on the C types directly without the round trip to Python and therefore fast). You could use merged = np.r_[a, b] to get concatenated numpy array. –  J.F. Sebastian  Apr 30 '14 at 3:38

You can use sets to obtain merged list of unique values

mergedlist = list(set(listone + listtwo))
share improve this answer
 
42 
this will lose ordering information. –  aaronasterling  Sep 20 '10 at 8:45
16 
True, however, it will also remove duplicates, if that's what you are interested in. List addition along would not do that. –  metasoarous  Aug 21 '12 at 0:28
4 
Better than listone + [x for x in listtwo if x not in listone] –  Natim  Jan 29 '13 at 13:13
1 
If I had a list of lists, such as this one:  [[0, 5], [1, 10], [0, 7], [3, 5]] How would you merge them to avoid duplicates in the key (first value in each sub-list), but if they are duplicates, end up with the sum of the second values? Like so:  [[0, 12], [1, 10], [3, 5]] Thanks –  jslvtr  Jul 23 '13 at 12:24
2 
+1 IMHO this is the correct way to "merge" (union) lists while the "approved" answer describes how to combine/add lists (multiset) –  alfasin  Apr 27 '14 at 4:07

This is quite simple, I think it was even shown in the tutorial:

>>> listone = [1,2,3]
>>> listtwo = [4,5,6]
>>>
>>> listone + listtwo
[1, 2, 3, 4, 5, 6]
share improve this answer
 

You could also do

listone = [1,2,3]
listtwo = [4,5,6]
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)
share improve this answer
 
 
@MatthewPurdon extend won't take a single item, it expects a list. –  mateor  Oct 15 '14 at 21:43

You could simply use the + or += operator as follows:

a = [1, 2, 3]
b = [4, 5, 6]

c = a + b

Or:

c = []
a = [1, 2, 3]
b = [4, 5, 6]

c += (a + b)

Also, if you want the values in the merged list to be unique you can do:

c = list(set(a + b))
share improve this answer
 

It's worth noting that the itertools.chain function accepts variable number of arguments:

>>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
>>> [i for i in itertools.chain(l1, l2)]
['a', 'b', 'c']
>>> [i for i in itertools.chain(l1, l2, l3)]
['a', 'b', 'c', 'd', 'e', 'f']

If an iterable (tuple, list, generator, etc.) is the input, the from_iterable class method may be used:

>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']
share improve this answer
 

With Python 3.3+ you can use yield from:

listone = [1,2,3]
listtwo = [4,5,6]

def merge(l1, l2):
    yield from l1
    yield from l2

>>> list(merge(listone, listtwo))
[1, 2, 3, 4, 5, 6]

Or, if you want to support an arbitrary number of iterators:

def merge(*iters):
    for it in iters:
        yield from it

>>> list(merge(listone, listtwo, 'abcd', [20, 21, 22]))
[1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 20, 21, 22]
share improve this answer
 

If you want to merge the two lists in sorted form, you can use merge function from the heapq library.

from heapq import merge

a = [1,2,4]
b = [2,4,6,7]

print list(merge(a,b))
share improve this answer
 

If you need to merge two ordered lists with complicated sorting rules, you might have to roll it yourself like in the following code (using a simple sorting rule for readability :-) ).

list1 = [1,2,5]
list2 = [2,3,4]
newlist = []

while list1 and list2:
    if list1[0] == list2[0]:
        newlist.append(list1.pop(0))
        list2.pop(0)
    elif list1[0] < list2[0]:
        newlist.append(list1.pop(0))
    else:
        newlist.append(list2.pop(0))

if list1:
    newlist.extend(list1)
if list2:
    newlist.extend(list2)

assert(newlist == [1, 2, 3, 4, 5])
share improve this answer
 

As a more general way for more lists you can put them within a list and use itertools.chain.from_iterable()1 function which based on THIS answer is the best way for flatting a nested list :

>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9] 

1. Note that chain.from_iterable() is available in python =>2.6.In other versions use chain(*l)

share improve this answer
 

If you don't want to or can't use the plus operator (+), you can uses the  __add__ function:

listone = [1,2,3]
listtwo = [4,5,6]

result = list.__add__(listone, listtwo)
print(result)

>>> [1, 2, 3, 4, 5, 6]
share improve this answer
 

You could use the append() method

mergedlist =[]
for elem in listone:
    mergedlist.append(elem)
for elem in listtwo:
    mergedlist.append(elem)
share improve this answer
 
4 
just so you know, if this is what you're doing in practice, this is much, much slower than the other proposed methods. see stackoverflow.com/questions/17479361/… –  Ryan Haining  Jul 16 '13 at 2:10
list1 = [1,2,3]
list2 = [4,5,6]

joinedlist = list1 + list2
#output : [1, 2, 3, 4, 5, 6]

Yes, its that simple.

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

share improve this answer
 

Joining two lists in Python:

>>> a = [1, 2, 3, 4]
>>> b = [1, 4, 6, 7]
>>> c = a + b 
>>> c
[1, 2, 3, 4, 1, 4, 6, 7]

If you don't want any duplication :

>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [5, 6, 7, 8]
>>> c = list(set(a + b)) 
>>> c
[1, 2, 3, 4, 5, 6, 7, 8]
share improve this answer
 

This question directly asks about joining two lists. However it's pretty high in search even when you are looking for a way of joining many lists (including the case when you joining zero lists). Consider this more generic approach:

a = [[1,2,3], [4,5,6], [7,8,9]]
reduce(lambda c, x: c + x, a, [])

Will output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Note, this also works correctly when a is [] or [[1,2,3]].

Update

Consider better alternative suggested by Patrick Collins in the comments:

sum(a, [])
share improve this answer
 
1 
cleaner: sum(a, []) –  Patrick Collins  Nov 18 '15 at 1:07 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值