In this tutorial, we will delve into the Python extend() method. This is a built-in function in Python that allows you to add multiple elements to a list at once. It’s an incredibly useful tool for managing and manipulating lists in Python.
What is the extend() method?
The extend() method adds all items of a list (or any iterable) to the end of the current list. It modifies the original list by adding new elements rather than creating a new one.
# Example list1 = ['apple', 'banana'] list2 = ['cherry', 'date'] list1.extend(list2) print(list1) # Output: ['apple', 'banana', 'cherry', 'date']
How does it differ from append()?
The append() method only adds its argument as a single element to the end of the list, while extend() can add multiple individual elements to the end of the list.
# Example list3 = ['elephant'] list4 = ['fox', 'giraffe'] list3.append(list4) print(list3) # Output: ['elephant', ['fox', 'giraffe']]
Proper Usage of extend()
To use extend(), simply call it on your list object and pass in an iterable (like another list) as an argument:
A Practical Example:
fruits = ["apple", "banana"] more_fruits = ["cherry", "date", "elderberry"] fruits.extend(more_fruits) print(fruits) # Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']
In the above example, we have a list of fruits. We then create another list of more fruits and extend our original list with this new one. The result is a combined list of all our fruits.
The extend() method is an efficient way to add multiple elements to your lists in Python. It’s important to remember that it modifies the original list and does not create a new one. Happy coding!