Combining Two Lists Using Various Methods
In this tutorial, we will learn about various methods of combining two lists in Python. These include using the ‘+’ operator, the extend() method, and the append() method. …
In this tutorial, we will learn about various methods of combining two lists in Python. These include using the ‘+’ operator, the extend() method, and the append() method.
The first way to combine or merge two lists is by using the ‘+’ operator. Here’s a simple example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
The second way to combine two lists is by using the extend() method. This method adds all elements of one list to another, but it does not create a new list. Here’s an example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
The third way to combine two lists is by using the append() method with a loop or list comprehension. Here’s an example of how to do this:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for item in list2:
list1.append(item)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
The append() method adds a single element to the end of a list, but it does not return any value and does not change the original list. If you want to create a new combined list with duplicate elements, use the ‘+=’ operator or extend().
Remember that these operations are not commutative; adding two lists together in one order doesn’t always give the same result as doing it in another order. For example, list1 + list2 followed by list1 += list2 is not the same as list1 += list2 followed by list1 + list2.