Python List extend() Method (with Examples)

Python List extend() Method: In this tutorial, we will learn about the extend() method of the list class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 20, 2023

Python List extend() Method

The extend() is an inbuilt method of the list class that is used to extend a list, it extends the list by inserting the list of the elements at the end of the current list. The method is called with this list (the current list, in which we have to add the elements), and another list (or any iterable) is supplied as an argument.

Syntax

The following is the syntax of extend() method:

list_name.index(iterable)

Parameter(s):

The following are the parameter(s):

  • iterable – It represents a list of the elements or any iterable.

Return Value

The return type of this method is <class 'NoneType'>, it returns nothing.

Example 1: Use of List extend() Method

# declaring the lists
cars = ["Porsche", "Audi", "Lexus", "Audi"]
more = ["Porsche", "BMW", "Lamborghini"]

# printing the lists
print("cars: ", cars)
print("more: ", more)

# extending the cars i.e. inserting
# the elements of more list into the list cars
cars.extend(more)

# printing the list after extending
print("cars: ", cars)

Output

cars:  ['Porsche', 'Audi', 'Lexus', 'Audi']
more:  ['Porsche', 'BMW', 'Lamborghini']
cars:  ['Porsche', 'Audi', 'Lexus', 'Audi', 'Porsche', 'BMW', 'Lamborghini']

Example 2: Use of List extend() Method

# declaring the list
x = [10, 20, 30]

print("x: ", x)

# inserting list elements and printing
x.extend([40, 50, 60])
print("x: ", x)

# inserting set elements and printing
x.extend({70, 80, 90})
print("x: ", x)

Output

x:  [10, 20, 30]
x:  [10, 20, 30, 40, 50, 60]
x:  [10, 20, 30, 40, 50, 60, 80, 90, 70]

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.