The extend() function in python helps to increase the length of the list by adding all the elements of given iterable to the end of the list.
list1.extend(iterable) #where iterable may be list, tuple, string etc.
The extend() function takes a single parameter. This method is similar to append() the difference is that append () adds a single element to the end of the list, but in extend() we can add multiple elements.
Parameter | Description | Required / Optional |
---|---|---|
Iterable | maybe list,tuple, string, etc. | Required |
This method doesn't return any value. It modifies the original list by adding elements.
# flowers list
flowers = ['Rose', 'Lotus', 'Jasmine']
# another list of flowers
flowers1 = ['Sunflower', 'Dalia']
# appending flowers1 elements to flowers
flowers.extend(flowers1)
Output:
Flowers List : ['Rose', 'Lotus', 'Jasmine','Sunflower', 'Dalia']
# flowers list
flowers = ['Dalia']
# flowers tuple
flowers_tuple = ('Rose', 'Lotus')
# flowers set
flowers_set = {'Jasmine', 'Sunflower'}
# appending flowers_tuple elements to flowers
flowers.extend(flowers_tuple)
print('New flowers List:', flowers)
# appending flowers_set elements to flowers
flowers.extend(flowers_set)
print('Newer flowers List:', flowers)
Output:
New flowers List: ['Dalia', 'Rose', 'Lotus'] Newer flowers List: ['Dalia', 'Rose', 'Lotus', 'Sunflower', 'Jasmine']
x1 = [1, 2]
x2 = [3, 4]
y = (5, 6)
# x1 = [1, 2, 5, 6]
x1.extend(y)
print(x1)
# x2 = [1, 2, (5, 6)]
x2.append(y)
print(x2)
Output:
[1, 2, 5, 6] [1, 2, (5, 6)]