How do I concatenate two lists in Python?
Example:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
Expected outcome:
>&g
Use a simple list comprehension:
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.
A really concise way to combine a list of lists is
list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
reduce(list.__add__, list_of_lists)
which gives us
[1, 2, 3, 4, 5, 6, 7, 8, 9]
a=[1,2,3]
b=[4,5,6]
c=a+b
print(c)
OUTPUT:
>>> [1, 2, 3, 4, 5, 6]
In the above code "+" operator is used to concatenate the 2 lists into a single list.
ANOTHER SOLUTION:
a=[1,2,3]
b=[4,5,6]
c=[] #Empty list in which we are going to append the values of list (a) and (b)
for i in a:
c.append(i)
for j in b:
c.append(j)
print(c)
OUTPUT:
>>> [1, 2, 3, 4, 5, 6]
You can use sets to obtain merged list of unique values
mergedlist = list(set(listone + listtwo))
Python >= 3.5
alternative: [*l1, *l2]
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.
This is quite simple, and 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]