How do I merge lists in Python safely and idiomatically?

In Python, merging lists can be done safely and idiomatically using various methods. Here are some approaches you can take to combine lists effectively.

Python, merge lists, list concatenation, list comprehension, idiomatic Python
Learn how to merge lists in Python using different methods such as list concatenation, using the `extend` method, or list comprehensions to create new data structures without losing elements.
# Merging lists using the '+' operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)  # Output: [1, 2, 3, 4, 5, 6]

# Merging lists using the extend() method
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]

# Merging lists using list comprehension
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [item for sublist in [list1, list2] for item in sublist]
print(merged_list)  # Output: [1, 2, 3, 4, 5, 6]
        

Python merge lists list concatenation list comprehension idiomatic Python