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]
The '+' operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.
📢 TLDR: Use + In almost all simple situations, using list1 + list2 is the way you want to concatenate lists. The edge cases below are better in some situations, but + is generally the best choice. All options covered work in Python 2.3, Python 2.7, and all versions of Python 31.
1) Using concatenation operation The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.
You can use the +
operator to combine them:
listone = [1, 2, 3] listtwo = [4, 5, 6] joinedlist = listone + listtwo
Output:
>>> joinedlist [1, 2, 3, 4, 5, 6]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With