![programmingoor.com how to concat 2 lists in python](https://programmingdoor.com/wp-content/uploads/2023/10/Blue-Bright-Youtube-Thumbnail-4-1024x576.png)
![programmingoor.com how to concat 2 lists in python](https://programmingdoor.com/wp-content/uploads/2023/10/Blue-Bright-Youtube-Thumbnail-4-1024x576.png)
You can concatenate two lists in Python using the +
operator or by using the extend()
method. Here are both methods:
Method 1: Using the +
Operator:
You can use the +
operator to concatenate two lists, creating a new list containing all the elements from both lists.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
Method 2: Using the extend()
Method:
You can also use the extend()
method to add all the elements from one list to another list. This method modifies the first list in place.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Both methods achieve the same result of combining the elements of two lists into a single list. The choice between them depends on whether you want to create a new list (using +
) or modify one of the existing lists (using extend()
).