Sobes.tech
Junior — Middle

How can the contents of multiple lists be combined into one list?

sobes.tech AI

Answer from AI

In Python, you can combine multiple lists into one in several ways:

  1. Operator + — creates a new list by concatenating the original lists:
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2  # [1, 2, 3, 4]
  1. Method extend() — adds elements from another list to the existing list:
list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)  # list1 is now [1, 2, 3, 4]
  1. itertools.chain() function — for merging many lists without creating intermediate lists:
import itertools
combined = list(itertools.chain(list1, list2, list3))
  1. Unpacking with * operator:
combined = [*list1, *list2]

The choice of method depends on whether you need to create a new list or modify an existing one.