Python List extend() - Adds Iterables to List
The extend()
method adds all the items from the specified iterable (list, tuple, set, dictionary, string) to the end of the list.
Syntax:
list.extend(iterable)
Parameters:
iterable: Any iterable (list, tuple, set, string, dict)
Return type:
No return value.
The following example demonstrates the extend()
method.
cities = ['Mumbai', 'London', 'Paris', 'New York']
newCities = ['Delhi', 'Chicago']
cities.extend(newCities)
print("Updated List: ", cities)
Updated List: ['Mumbai', 'London', 'Paris', 'New York', 'Delhi', 'Chicago']
The following adds a tuple elements to a list.
cities = ['Mumbai', 'London', 'Paris', 'New York']
cities_tup = ('Delhi','Chicago')
cities.extend(cities_tup)
print("Updated List: ", cities)
Updated List: ['Mumbai', 'London', 'Paris', 'New York', 'Delhi', 'Chicago']
The following adds a set elements to a list.
cities = ['Mumbai', 'London', 'Paris', 'New York']
cities_set = {'Delhi','Chicago'}
cities.extend(cities_set)
print("Updated List: ",cities)
Updated List: ['Mumbai', 'London', 'Paris', 'New York', 'Delhi', 'Chicago']
The following adds a dictionary keys to list.
cities = ['Mumbai', 'London', 'Paris', 'New York']
capitals = {'New Delhi':'India','Washington DC':'USA'}
cities.extend(capitals) # adds keys of dict as elements
print("Updated List: ",cities)
Updated List: ['Mumbai', 'London', 'Paris', 'New York', 'New Delhi', 'Washington DC']
Extend Iterable Using the + Operator
The +
operator can also be used to extend the iterable objects. However, it can only be used with the same type of iterables e.g. adding list to list, tuple to tuple.
cities = ['Mumbai', 'London']
favcities = ['Paris', 'New York']
cities = cities + favcities # or cities += favcities
print("Cities: ", cities)
Cities: ['Mumbai', 'London', 'Paris', 'New York']
extend() vs append()
The extend()
method adds items of the specified iterable at the end of the list, whereas the append()
method adds the whole iterable as an item at the end of the list.
cities = ['Mumbai', 'London']
bigcities = ['Washington DC', 'Banglore']
favcities = ['Paris', 'New York']
cities.extend(favcities)
bigcities.append(favcities)
print("Cities: ", cities)
print("Big Cities: ", bigcities)
Cities: ['Mumbai', 'London', 'Paris', 'New York']
Big Cities: ['Washington DC', 'Banglore', ['Paris', 'New York']]