How to concatenate two Lists ?

Bloghow topython
programmingoor.com how to concat 2 lists in python

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()).

Leave a Reply

Your email address will not be published. Required fields are marked *