Menu Close

Python List extend() method

Python list extend() method

In this tutorial, you will learn about the Python list extend() method. The list extends function is used to add any iterable elements ( list, set, tuple, string ) to the end of the list. Python list extend() method is best when you want to extend your list.
In the previous tutorial we have seen, the Python list copy() and list count() methods.

List extend() method

In Python, the extend() method is a list method that is used to Add the elements of a list (or any iterable ). To the end of the current list. Sometimes you need to extend your list, Then you can use the list extend function.

Syntax of list extend() method:

list.extend(iterable)

List extend() method parameter:

Python list extend method takes a single parameter, which is iterable. Python Iterable can be anything:- List, Tuple, Set, String, etc.

iterable:– Required. Any iterable (list, set, tuple, etc.)

Return type of list extend() method:

Python list extend() method modified the original list, It does not return any value.

List extend() method Example:

Example 1:

Add tuple items to the list using the list extend() function.

fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.extend(points)
print(fruits)

Output:

['apple', 'banana', 'cherry', 1, 4, 5, 9]

Example 2:

Add items from one list to another list.

x = [1,2,3,4,5,6]
y = [7,8,9,10]
x.extend(y)
print(x)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 3:

Add Python sets item to the list using the extend() function.

full_name = ['Vishvajit', 'Rao']
details = {'Noida', 'Software Enginner'}
full_name.extend(details)
print(full_name)

Output

['Vishvajit', 'Rao', 'Software Enginner', 'Noida']

Another way to extend a list:

a. To extend a list, you can use the + operator.

x = [1,2,3,4,5,6]
y = [7,8,9,10]
result = x + y
print(result)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

b. Using slice syntax, you can extend the list.

x = [1,2,3,4,5,6]
y = [7,8,9,10]
x[len(x):] = y
print(x)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Other Useful Articles:

Conclusion:

In this tutorial, you have learned what is the Python list extend() method to extend the existing list with other elements. The extend() method is a very useful method to extend the existing list, It modifies the original list and returns None.

I hope this article will help you, If you like this article, Please comment and share it with your friends who want to learn Python programming from scratch to advanced.

For More Reference:- Click Here

Python List clear() Method
Python List index() Method

Related Posts