Junior — Middle
How to combine two lists into one?
sobes.tech AI
Answer from AI
In Python, two lists can be combined in several ways:
- Using the
+operator:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]
- Using the
extend()method, which adds the elements of the second list to the first:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
- Using list unpacking (Python 3.5+):
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = [*list1, *list2]
print(combined) # [1, 2, 3, 4, 5, 6]
All these methods create a new list or modify the existing one, combining elements from the two lists.