In this article, we will discuss about the usage details of extend()
method of List in Python.
Table Of Contents
Introduction
The extend()
method of List accepts an iterable sequence (like list
, tuple
, set
, string
etc.) as an argument. It extends the calling list object, by adding all the elements of given iterable sequence into the list.
Syntax of List extend() method
listObject.extend(iterable)
Adds all the elements from the given iterable
sequence into the calling list object.
Parameters
iterable
: A sequence whose elements needs to be added in list. This sequence can be a list, a tuple, a set, or any other sequence.
Returns
It doesn’t returns anything. Basically the return value is None. But it extends the calling list object, by appending elements from the given iterable.
Example of List extend() method
Suppose we have two lists,
listOfNumbers = [11, 22, 33, 44, 55] anotherList = [99, 98, 97, 96, 95]
We want to append all the elements of anotherList
into the first list i.e. listOfNumbers
. For that, we will call the extend()
of list listOfNumbers
, and pass another list object i.e. anotherList
in it, as argument. It will add the elements of list anotherList
into the calling list object i.e. listOfNumbers
. Let’s see the complete example,
listOfNumbers = [11, 22, 33, 44, 55] anotherList = [99, 98, 97, 96, 95] # Add all elements of anotherList into listOfNumbers listOfNumbers.extend(anotherList) print(listOfNumbers)
Output:
[11, 22, 33, 44, 55, 99, 98, 97, 96, 95]
It added all the elements of second list into the first list.
Add all elements of a tuple to list
In the extend() method of list, we can pass any iterable sequence. For example, we can pass a tuple as argument in the extend() method, and it will add the elements of tuple into the calling list object. Let’s see the complete example,
listOfNumbers = [11, 22, 33, 44, 55] tupleObj = (99, 98, 97, 96, 95) # Add all elements of tuple into the list listOfNumbers.extend(tupleObj) print(listOfNumbers)
Output:
[11, 22, 33, 44, 55, 99, 98, 97, 96, 95]
It added all the elements of tuple into the list.
Summary
We learned all about the extend() method of List in Python.