Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Python - List extend() Method



The Python list extend() method is used to add all elements of an iterable at end of the list. An iterable object can be any data structure like list, tuple, set, string, dictionary and range iterables etc.

Syntax

list.extend(iterable)

Parameters

iterable Required. iterable object like list, tuple, set, string , dictionary, etc.

Return Value

None.

Example: Using list, tuple, set iterables

Below example explains how to use list extend() method with different iterables like - list, tuple and set, etc.

#using list iterable
MyList = [1, 2]
MyList.extend([3, 4])
print(MyList)

#using tuple iterable
MyList.extend((5, 6))
print(MyList)

#using set iterable
MyList.extend({7, 8})
print(MyList)

The output of the above code will be:

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

Example: Using string iterable

In the example below, list extend() method is used with string iterable.

MyList = ['H', 'i']
MyList.extend('John')
print(MyList)

The output of the above code will be:

['H', 'i', 'J', 'o', 'h', 'n']

Example: Using dictionary iterable

The example below describes how to use list extend() method with dictionary iterable.

MyDict = {
  'name': 'John',
  'age': 25,
  'city': 'London'
}

MyList = []
MyList.extend(MyDict)
print(MyList)

MyList = []
MyList.extend(MyDict.keys())
print(MyList)

MyList = []
MyList.extend(MyDict.values())
print(MyList)

The output of the above code will be:

['name', 'age', 'city']
['name', 'age', 'city']
['John', 25, 'London']

❮ Python List Methods

5