Home »
Python
Python List extend() Method with Example
Python List extend() Method: Here, we are going to learn how extend a list i.e. how to add a list of the elements to the list?
Submitted by IncludeHelp, on December 04, 2019
List extend() Method
extend() method 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 (current list, in which we have to add the elements) and another list (or any iterable) is supplied as an argument.
Syntax:
list_name.index(iterable)
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:
# Python List extend() Method with Example
# 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:
# Python List extend() Method with Example
# 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]
TOP Interview Coding Problems/Challenges