In Python, you can merge two lists using several methods:
- Using the + Operator: The simplest way to merge two lists is by using the + operator, which combines both lists into one.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]
- Using the extend() Method: The extend() method appends the elements of one list to another in place.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
- Using the itertools.chain() Function: The chain() function from the itertools module allows you to merge lists efficiently.
from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list(chain(list1, list2))
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]
These methods allow for easy and flexible list merging in Python.