It’s also possible to create a generator that simply iterates over the items in both lists using itertools.chain(). 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
Another alternative has been introduced via the acceptance of PEP 448 which deserves mentioning.
The PEP, titled Additional Unpacking Generalizations, generally reduced some syntactic restrictions when using the starred * expression in Python; with it, joining two lists (applies to any iterable) can now also be done with:
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> joined_list = [*l1, *l2] # unpack both iterables in a list literal
>>> print(joined_list)
[1, 2, 3, 4, 5, 6]
This functionality was defined for Python 3.5 it hasn’t been backported to previous versions in the 3.x family. In unsupported versions a SyntaxError is going to be raised.
As with the other approaches, this too creates as shallow copy of the elements in the corresponding lists.
The upside to this approach is that you really don’t need lists in order to perform it, anything that is iterable will do. As stated in the PEP:
This is also useful as a more readable way of summing iterables into a
list, such as my_list + list(my_tuple) + list(my_range) which is now
equivalent to just [*my_list, *my_tuple, *my_range].
So while addition with + would raise a TypeError due to type mismatch:
l = [1, 2, 3]
r = range(4, 7)
res = l + r
The following won’t:
res = [*l, *r]
because it will first unpack the contents of the iterables and then simply create a list from the contents.
As of 3.7, these are the most popular stdlib methods for concatenating two (or more) lists in python.
Footnotes
This is a slick solution because of its succinctness. But sum performs concatenation in a pairwise fashion, which means this is a
quadratic operation as memory has to be allocated for each step. DO
NOT USE if your lists are large.
See chain
and
chain.from_iterable
from the docs. You will need to import itertools first.
Concatenation is linear in memory, so this is the best in terms of
performance and version compatibility. chain.from_iterable was introduced in 2.6.
a += b and a.extend(b) are more or less equivalent for all practical purposes. += when called on a list will internally call
list.__iadd__, which extends the first list by the second.
Performance
2-List Concatenation1
There’s not much difference between these methods but that makes sense given they all have the same order of complexity (linear). There’s no particular reason to prefer one over the other except as a matter of style.
1. The iadd (+=) and extend methods operate in-place, so a copy has to be generated each time before testing. To keep things fair, all methods have a pre-copy step for the left-hand list which can be ignored.
Comments on Other Solutions
DO NOT USE THE DUNDER METHOD list.__add__ directly in any way, shape or form. In fact, stay clear of dunder methods, and use the operators and operator functions like they were designed for. Python has careful semantics baked into these which are more complicated than just calling the dunder directly. Here is an example. So, to summarise, a.__add__(b) => BAD; a + b => GOOD.
Some answers here offer reduce(operator.add, [a, b]) for pairwise concatenation — this is the same as sum([a, b], []) only more wordy.
Any method that uses set will drop duplicates and lose ordering. Use with caution.
for i in b: a.append(i) is more wordy, and slower than a.extend(b), which is single function call and more idiomatic. append is slower because of the semantics with which memory is allocated and grown for lists. See here for a similar discussion.
heapq.merge will work, but its use case is for merging sorted lists in linear time. Using it in any other situation is an anti-pattern.
yielding list elements from a function is an acceptable method, but chain does this faster and better (it has a code path in C, so it is fast).
operator.add(a, b) is an acceptable functional equivalent to a + b. It’s use cases are mainly for dynamic method dispatch. Otherwise, prefer a + b which is shorter and more readable, in my opinion. YMMV.
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).
I think the best option is to use list comprehensions:
>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> [x for xs in a for x in xs]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You can create generators as well:
>>> map(str, (x for xs in a for x in xs))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Old Answer
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]].
However, this can be done more efficiently with itertools:
a = [[1,2,3], [4,5,6], [7,8,9]]
list(itertools.chain(*a))
If you don’t need a list, but just an iterable, omit list().
Update
Alternative suggested by Patrick Collins in the comments could also work for you:
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))
回答 9
值得注意的是,该itertools.chain函数接受可变数量的参数:
>>> 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']
如果输入一个可迭代的(元组,列表,生成器等),from_iterable则可以使用class方法:
>>> il =[['a'],['b','c'],['d','e','f']]>>>[i for i in itertools.chain.from_iterable(il)]['a','b','c','d','e','f']
As a more general way for more lists you can put them within a list and use the itertools.chain.from_iterable()1 function which based on this answer is the best way for flatting a nested list:
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])
回答 15
您可以使用append()在list对象上定义的方法:
mergedlist =[]for elem in listone:
mergedlist.append(elem)for elem in listtwo:
mergedlist.append(elem)
As already pointed out by many, itertools.chain() is the way to go if one needs to apply exactly the same treatment to both lists. In my case, I had a label and a flag which were different from one list to the other, so I needed something slightly more complex. As it turns out, behind the scenes itertools.chain() simply does the following:
for it in iterables:
for element in it:
yield element
for iterable, header, flag in ( (newList, 'New', ''), (modList, 'Modified', '-f')):
print header + ':'
for path in iterable:
[...]
command = 'cp -r' if os.path.isdir(srcPath) else 'cp'
print >> SCRIPT , command, flag, srcPath, mergedDirPath
[...]
The main points to understand here are that lists are just a special case of iterable, which are objects like any other; and that for ... in loops in python can work with tuple variables, so it is simple to loop on multiple variables at the same time.
回答 18
使用简单的列表理解:
joined_list =[item for list_ in[list_one, list_two]for item in list_]
joined_list = [item for list_ in [list_one, list_two] for item in list_]
It has all the advantages of the newest approach of using Additional Unpacking Generalizations – i.e. you can concatenate an arbitrary number of different iterables (for example, lists, tuples, ranges, and generators) that way – and it’s not limited to Python 3.5 or later.
import itertools
A = list(zip([1,3,5,7,9],[2,4,6,8,10]))
B =[1,3,5,7,9]+[2,4,6,8,10]
C = list(set([1,3,5,7,9]+[2,4,6,8,10]))
D =[1,3,5,7,9]
D.append([2,4,6,8,10])
E =[1,3,5,7,9]
E.extend([2,4,6,8,10])
F =[]for a in itertools.chain([1,3,5,7,9],[2,4,6,8,10]):
F.append(a)print("A: "+ str(A))print("B: "+ str(B))print("C: "+ str(C))print("D: "+ str(D))print("E: "+ str(E))print("F: "+ str(F))
def concatenate_list(listOne, listTwo):
joinedList =[]for i in listOne:
joinedList.append(i)for j in listTwo:
joinedList.append(j)
sorted(joinedList)return joinedList
If you wanted a new list whilst keeping the two old lists:
def concatenate_list(listOne, listTwo):
joinedList = []
for i in listOne:
joinedList.append(i)
for j in listTwo:
joinedList.append(j)
sorted(joinedList)
return joinedList