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 extends your list.
In the previous tutorial we have seen, Python list copy() and list count() method.

List extend() method

In Python, extend() method is list method which is used Add the elements of a list (or any iterable ). To the end of the current list. Sometimes you need to extends your list, Then you can use 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.
iterable can be anything:- List, Tuple, Set, String, etc.

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

Return type of list extend() method:

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 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 of one list to the 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 extend function.

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

Output

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

Other way to extend a list:

a. To extend a list, you can use + 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]

Conclusion:

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

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

For More Reference:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply