Python extend List Function

Python extend function is useful to add a new list to the end of an old one. In this section, we discuss how to use this extend method with practical examples and the syntax is:

Old.extend(New)

This method helps us to add all the items in New at the end of the Old.

Python extend List Function Example

This method append and extend given elements to the list. The below code add b to the end of a

a = [10, 20, 30, 40]
b = [70, 120]

print("Original Items are : ", a)
a.extend(b)
print("New Items are      : ", a)
Original Items are :  [10, 20, 30, 40]
New Items are      :  [10, 20, 30, 40, 70, 120]

In this example, we declared two string elements. Next, we used this function on them.

TIP: Please refer to List article and functions article to understand everything about them in Python programming language.

Fruits = ['Apple', 'Orange', 'Kiwi']
strFruit = ['Banana', 'Cherry']

print("Original Items are : ", Fruits)
Fruits.extend(strFruit)
print("Items After are    : ", Fruits)
Python Extend List Function 3

Let me use this on the Mixed elements. I mean, adding a string to an integer.

a = [10, 20, 30, 40]
b = ['Apple', 'Kiwi']

print("Original Items are : ", a)
a.extend(b)
print("Items are          : ", a)
Original Items are :  [10, 20, 30, 40]
Items are          :  [10, 20, 30, 40, 'Apple', 'Kiwi']

In this program, we used this one on the Nested.

Nested = [[71, 222], [22, 13], [99, 77]]
NewOne = [[11, 22], [44, 55]]

print("Original Elements are : ", Nested)
Nested.extend(NewOne)
print("Elements are          : ", Nested)
Original Elements are :  [[71, 222], [22, 13], [99, 77]]
Elements are          :  [[71, 222], [22, 13], [99, 77], [11, 22], [44, 55]]