博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How to append list to second list
阅读量:4032 次
发布时间:2019-05-24

本文共 8169 字,大约阅读时间需要 27 分钟。

641
77

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]
 
1  
what about if listone was [3,2,1]? Will the output change? –   
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 ;) –   
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) –   
Sep 12 '14 at 3:31 
 
Isn’t this operation called concatination rather than merging? I always thought merging means concatination + sorting. –   
Nov 8 '14 at 2:33 
 
This question's searchability could be improved if the terms 'looping' and 'concatenate' were added. – 
Sep 9 '15 at 13:22

17 Answers

1171
accepted

Python makes this ridiculously easy.

mergedlist = listone + listtwo
 
24  
does this create a deep copy of listone and appends listtwo? –   
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. –   
Apr 19 '12 at 14:51
47  
another useful detail here: listone += listtwo results in listone == [1, 2, 3, 4, 5, 6] –   
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? –   
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. –   
Feb 20 '14 at 18:55
104

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 itertoolsfor item in itertools.chain(listone, listtwo):   # do something with each list item
 
9  
This is better way because it also works with numpy array. –   
Sep 25 '12 at 9:37
1  
will this work the same way: mergedList = itertools.chain(listone, listtwo) for item in mergedList: –   
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. –   
Apr 30 '14 at 3:38
85

You can use sets to obtain merged list of unique values

mergedlist = list(set(listone + listtwo))
 
42  
this will lose ordering information. –   
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. –   
Aug 21 '12 at 0:28
4  
Better than listone + [x for x in listtwo if x not in listone] –   
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 –   
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) –   
Apr 27 '14 at 4:07
31

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

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

You could also do

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

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))
 
11

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']
 
9

With Python 3.3+ you can use :

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]
 
7

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

from heapq import mergea = [1,2,4]b = [2,4,6,7]print list(merge(a,b))
 
4

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])
 
3

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  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)

 
3

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]
 
2

You could use the append() method

mergedlist =[]for elem in listone:    mergedlist.append(elem)for elem in listtwo:    mergedlist.append(elem)
 
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  –   
Jul 16 '13 at 2:10
1
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

 
1

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]
 
1

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, [])
 
1  
cleaner: sum(a, []) –   
Nov 18 '15 at 1:07 

转载地址:http://uihbi.baihongyu.com/

你可能感兴趣的文章
POJ 2535 Very Simple Problem(我的水题之路——看错题)
查看>>
POJ 2538 WERTYU(我的水题之路——键盘错位)
查看>>
POJ 2551 Ones(我的水题之路——重点,末尾有几个1)
查看>>
POJ 2562 Primary Arithmetic(我的水题之路——模拟加法进位)
查看>>
POJ 2575 Jolly Jumpers(我的水题之路——数组绝对差值为1到n-1)
查看>>
POJ 2578 Keep on Truckin'(我的水题之路——谁先大于168)
查看>>
POJ 2579 Blurred Vision(我的水题之路——四方格平均值)
查看>>
POJ 2591 Set Definition(我的水题之路——又一个丑数)
查看>>
POJ 2606 Rabbit hunt(我的水题之路——斜率最多)
查看>>
POJ 2608 Soundex(我的水题之路——字符值)
查看>>
POJ 2636 Electrical Outlets(我的水题之路——水,电器接头)
查看>>
POJ 2656 Unhappy Jinjin(我的水题之路——不开心的学习日)
查看>>
POJ 2664 Prerequisites?(我的水题之路——选课)
查看>>
POJ 2665 Trees(我的水题之路——移树,POJ100题啦!)
查看>>
POJ 2840 Big Clock(我的水题之路——水,钟)
查看>>
POJ 2864 Pascal Library(我的水题之路——都来了么)
查看>>
POJ 2871 A Simple Question of Chemistry(我的水题之路——数列两数之差 )
查看>>
POJ 2909 Goldbach's Conjecture(我的水题之路——任一数为素数对之和)
查看>>
POJ 2924 Gauß in Elementary School(我的水题之路——n到m的连和)
查看>>
POJ 3006 Dirichlet's Theorem on Arithmetic Progressions(我的水题之路——加i个d后的第几个素数)
查看>>