The extend()
method in Python is a list method that is used to extend a list by appending elements from another iterable object like a list, tuple, set, etc. It modifies the original list in place by adding elements from the specified iterable object to the end of the list.
Parameter Values
Parameter | Description |
---|---|
iterable | An iterable object (such as a list, tuple, set, etc.) containing elements to extend the list with. |
Return Values
The extend()
method in Python has a return type of None
. It modifies the list in place.
How to Use extend()
in Python
Example 1:
The extend()
method adds all the elements of an iterable (list, tuple, set, etc.) to the end of the list.
numbers = [1, 2, 3]
more_numbers = [4, 5, 6]
numbers.extend(more_numbers)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
Example 2:
It can also be used to concatenate multiple lists into one.
list1 = ['a', 'b']
list2 = ['c', 'd']
list3 = ['e', 'f']
list1.extend(list2)
list1.extend(list3)
print(list1) # Output: ['a', 'b', 'c', 'd', 'e', 'f']
Example 3:
The extend()
method modifies the original list and does not return a new list.
my_list = [1, 2, 3]
new_items = (4, 5, 6)
my_list.extend(new_items)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]