Python List extend() Method
Last Updated :
10 Dec, 2024
Improve
In Python, extend() method is used to add items from one list to the end of another list. This method modifies the original list by appending all items from the given iterable.
Using extend() method is easy and efficient way to merge two lists or add multiple elements at once.
Let’s look at a simple example of the extend() method.
a = [1, 2, 3]
b = [4, 5]
# Using extend() to add elements of b to a
a.extend(b)
print(a)
Output
[1, 2, 3, 4, 5]
Explanation: The elements of list b are added to the end of list a. The original list a is modified and now contains [1, 2, 3, 4, 5].
Syntax of List extend() Method
list_name.extend(iterable)
Parameters:
- list_name: The list that will be extended
- iterable: Any iterable (list, set, tuple, etc.)
Returns:
- Python List extend() returns none.
Using extend() with Different Iterables
The extend() method can work with various types of iterables such as: Lists, Tuples, Sets and Strings (each character will be added separately)
Example:
# Using a tuple
a = [1, 2, 3]
b = (4, 5)
a.extend(b)
print(a)
# Using a set
a = [1, 2, 3]
b = {4, 5}
a.extend(b)
print(a)
# Using a string
a = ['a', 'b']
b = "cd"
a.extend(b)
print(a)
Output
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] ['a', 'b', 'c', 'd']
Also Read - Python List Methods
Similar Article on List extend: