How do I concatenate two lists in Python?
There are a few ways to concatenate lists in Python. Here are a few options:
- Use the
+operator:
list3 will be equal to [1, 2, 3, 4, 5, 6].
- Use the
extend()method:
list1 will be equal to [1, 2, 3, 4, 5, 6].
- Use list comprehension:
list3 will be equal to [1, 2, 3, 4, 5, 6].
- Use the
itertoolsmodule:
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 all of these methods will create a new list, rather than modifying the original lists. If you want to modify the original lists in place, you can use the += operator or the extend() method.