How do I concatenate two lists in Python? How do I concatenate two lists in Python? python python

How do I concatenate two lists in Python?

You can use the + operator to combine them:

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


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

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 itertoolsfor item in itertools.chain(listone, listtwo):    # Do something with each list item