How do I concatenate two lists in Python?

There are a few ways to concatenate lists in Python. Here are a few options:

  1. Use the + operator:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2

list3 will be equal to [1, 2, 3, 4, 5, 6].

  1. Use 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].

Watch a course Python - The Practical Guide

  1. Use list comprehension:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [x for x in list1 + list2]

list3 will be equal to [1, 2, 3, 4, 5, 6].

  1. Use the 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 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.