Python List - extend() Method
The Python 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