How do I concatenate two lists in Python?
There are a few ways to concatenate lists in Python.
There are a few ways to concatenate lists in Python. Here are a few options:
- Use the
+operator:
Concatenating lists in Python using the + operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2list3 will be equal to [1, 2, 3, 4, 5, 6].
- Use the
extend()method:
Concatenating lists in Python using the extend method
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)list1 will be equal to [1, 2, 3, 4, 5, 6].
- Use the unpacking syntax:
Concatenating lists in Python using unpacking
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [*list1, *list2]list3 will be equal to [1, 2, 3, 4, 5, 6].
- Use the
itertoolsmodule:
Concatenating lists in Python using itertools module
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list(itertools.chain(list1, list2))list3 will be equal to [1, 2, 3, 4, 5, 6]. Note that itertools.chain is ideal for concatenating multiple iterables. For a single iterable containing multiple iterables, itertools.chain.from_iterable() is more efficient.
Note that the + operator, unpacking, and itertools.chain all create a new list. If you want to modify the original list in place, use the extend() method or the += operator.