Have you ever wondered: “How to add elements of one list to another?” The extend method of Python helps you to do exactly this.It is an in-build method that adds elements of specified list to the end of the current list. Since it is a method of class list, you use it by using dot(.) Operator on list. It doesn’t return any value but add the content to the existing list. Extend method iterates over its argument by adding each element to the list and extending the list. This means it works on any iterators like list, tuple, set and even string. But when used with string, each character of string is appended as an individual element in the list.
Syntax of Extend Method
list1.extend(list2)
Above code adds all the elements of list2 at the end of list1. It takes a single argument and adds it to the end of list.
To add the element of other data types like tuples and set to the list, use one of these methods:
- list.extend(list(tuple_data))
- list.extend(tuple_data)
Adding a List using Extend() Method
# Creating a First List
workers_name = ['Jhon', 'Neil', 'Adam']
print("Content of workers_name list: ", workers_name)
# Another list of city
department = ['Admin', 'Manager']
print("Contents of department list: ", department)
department.extend(workers_name)
# Extended List
print('Contents of department list after department.extend(workers_name):', workers_name)
The output will be
Output:
Content of workers_name list: ['Jhon', 'Neil', 'Adam']
Content of department list: ['Admin', 'Manager']
Contents of department list after department.extend(workers_name): ['Admin', 'Manager', 'Jhon', 'Neil', 'Adam']
Add elements of Tuple and Set to List
# Creating a First list
list_1 = ['Learn', 'Python', 'Well']
print("List is: ",list_1)
# Creating a tuple
tuple_data = ('Pickup', 'Brain')
print("Tuple is: ",tuple_data)
# Creating a set
set_data = {'Knowledge', 'is', 'Wealth'}
print("Set is: ",set_data)
# Appending element of tuple
list_1.extend(tuple_data)
print('List and Tuple data: ', list_1)
# Appending element of set
list_1.extend(set_data)
print('List and Set data: ', list_1)
The output will be
Output:
List is: ['Learn', 'Python', 'Well']
Tuple is: ('Pickup', 'Brain')
Set is: {'Wealth', 'Knowledge', 'is'}
List and Tuple data: ['Learn', 'Python', 'Well', 'Pickup', 'Brain']
List and Set data: ['Learn', 'Python', 'Well', 'Pickup', 'Brain', 'Wealth', 'Knowledge', 'is']
The Python data types like tuples and sets passed to extend() method are converted automatically to a list before appending to the list.
Conclusion
Unlike Append method which adds an entire argument as an single element to the list, the extend method iterates over its argument by adding each element to the list and extending the list.
C P Gupta is a YouTuber and Blogger. He is expert in Microsoft Word, Excel and PowerPoint. His YouTube channel @pickupbrain is very popular and has crossed 9.9 Million Views.