Python Tutorial

# Merge Two Lists in Python

In Python, concatenating two lists means combining them into a single list. There are a few ways to achieve this. Here's a detailed explanation with examples:

## Using the + Operator

list1 = [1, 2, 3] list2 = [4, 5, 6] concatenated_list = list1 + list2 print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]

You can simply use the + operator to concatenate two lists, resulting in a new list that includes all elements from both 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]

The extend() method modifies the first list by adding all elements from the second list to it.

## Using List Slicing

list1 = [1, 2, 3] list2 = [4, 5, 6] list1[len(list1):] = list2 print(list1) # Output: [1, 2, 3, 4, 5, 6]

This method is less commonly used, but it involves using list slicing to append the elements of the second list to the end of the first list.

## Using List Comprehension

list1 = [1, 2, 3] list2 = [4, 5, 6] concatenated_list = [item for sublist in [list1, list2] for item in sublist] print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]

List comprehension can also be used to concatenate lists by iterating over each sublist and its elements.

### Conclusion

Merging two lists in Python involves combining their elements into a single list. This can be achieved using the + operator, the extend() method, list slicing, or list comprehension, each offering distinct approaches to achieving the same outcome.