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 and dictionary etc. An iterable created by range() function can also be used here.
Syntax
list.extend(iterable)
Parameters
iterable |
Required. iterable object like list, tuple, set, string , dictionary, etc. |
Return Value
None.
Example: Using list, tuple, set as iterable
Below example explains how to use list extend() method with different iterables like - list, tuple and set, etc.
#using list as an iterable MyList = [1, 2] MyList.extend([3, 4]) print(MyList) #using tuple as an iterable MyList.extend((5, 6)) print(MyList) #using set as an 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 as iterable
In the below example, 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 as iterable
The below example 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