Tutorial Study Image

Python extend()

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.


 

extend() Parameters:

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

extend() Return Value

This method doesn't return any value. It modifies the original list by adding elements.

Examples of extend() method in Python

Example 1: How to works extend() method in Python


# 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']

Example 2: How to add elements of Tuple and Set to list?


# 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']

Example 3: How extend() & append() works in Python?


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)]