How to concatenate two lists in Python?

y2k Source

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

Answers

answered 9 years ago Daniel G #1

You can use the + operator to combine them:

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

mergedlist = listone + listtwo

Output:

>>> mergedlist
[1,2,3,4,5,6]

answered 9 years ago Tuure Laurinolli #2

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]

answered 9 years ago Robert Rossney #3

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

answered 8 years ago Radagast #4

You can use sets to obtain merged list of unique values

mergedlist = list(set(listone + listtwo))

answered 5 years ago Gourneau #5

You could also use extend in order to add a list add the end of another one:

listone = [1,2,3]
listtwo = [4,5,6]
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)

answered 5 years ago Dariusz Walczak #6

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

answered 5 years ago Amyth #7

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

answered 5 years ago mingxiao #8

You could use the append() method defined on list objects:

mergedlist =[]
for elem in listone:
    mergedlist.append(elem)
for elem in listtwo:
    mergedlist.append(elem)

answered 5 years ago Mr Shark #9

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

answered 4 years ago user688635 #10

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]

answered 4 years ago jpihl #11

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

Alternatively, if you don't like the use of dunders you can use the operator import:

import operator

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

result = operator.add(listone, listtwo)
print(result)

>>> [1, 2, 3, 4, 5, 6]

One could argue this is a bit more readable.

answered 3 years ago Kasramvd #12

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)

answered 3 years ago lavee_singh #13

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

answered 3 years ago shiminsh #14

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]

answered 3 years ago wonder.mice #15

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

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:

sum(a, [])

answered 3 years ago Francesco Marchetti-Stasi #16

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

(see https://docs.python.org/2/library/itertools.html), so I took inspiration from here and wrote something along these lines:

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.

answered 2 years ago Jim Fasarakis Hilliard #17

Python >= 3.5 alternative: [*l1, *l2]

Even though this is an old answer, 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]

#unpack both iterables in a list literal
>>> joinedList = [*l1, *l2]
>>> print(joinedList)
[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.

answered 2 years ago AceLearn #18

list(set(listone) | set(listtwo))

The above code, does not preserve order, removes duplicate from each list (but not from the concatenated list)

answered 1 year ago James Miller #19

lst1 = [1,2]

lst2 = [3,4]

def list_combinationer(Bushisms, are_funny):

    for item in lst1:
        lst2.append(item)
        lst1n2 = sorted(lst2)
        print lst1n2

list_combinationer(lst1, lst2)

[1,2,3,4]

answered 1 year ago Ukendar Vadivel #20

If you wanted a new list whilst keeping the two old lists:

joinedList = []
for i in listOne:
    joinedList.append(i)
for j in listTwo:
    joinedList.append(j)

sorted(joinedList)

return joinedList

answered 4 months ago JamesVeug #21

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

Output:

A: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
C: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

answered 4 months ago py-D #22

You can go for extend function.

l1 = [1,2,3]
l2 = [4,5,6]
l1.extend(l2)
print l1

output: [1,2,3,4,5,6]

answered 3 months ago Akash Singh #23

A really concise way to add a list of lists is

li = [[1,2,3], [4,5,6], [7,8,9]]
reduce(list.__add__,li)

which gives us

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

answered 2 months ago Moses S #24

You can use extends function

listone.extends(listtwo)

answered 2 weeks ago o'rety #25

I'm surprised it seems nobody proposed using a simple list comprehension:

joined_list = [y for x in [list_one, list_two] for y in x]

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 (e.g. lists, tuples, ranges, generators) that way - and it's not limited to Python >= 3.5.

comments powered by Disqus