Join our newsletter for the latest updates.

Python List extend()

In this tutorial, we will learn about the Python List extend() method with the help of examples.

The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.

Example

# create a list
prime_numbers = [2, 3, 5]

# create another list
numbers = [1, 4]

# add all elements of prime_numbers to numbers numbers.extend(prime_numbers)
print('List after extend():', numbers) # Output: List after extend(): [1, 4, 2, 3, 5]

Syntax of List extend()

The syntax of the extend() method is:

list1.extend(iterable)

Here, all the elements of iterable are added to the end of list1.


extend() Parameters

As mentioned, the extend() method takes an iterable such as list, tuple, string etc.


Return Value from extend()

The extend() method modifies the original list. It doesn't return any value.


Example 1: Using extend() Method

# languages list
languages = ['French', 'English']

# another list of language
languages1 = ['Spanish', 'Portuguese']

# appending language1 elements to language languages.extend(languages1)
print('Languages List:', languages)

Output

Languages List: ['French', 'English', 'Spanish', 'Portuguese']

Example 2: Add Elements of Tuple and Set to List

# languages list
languages = ['French']

# languages tuple
languages_tuple = ('Spanish', 'Portuguese')

# languages set
languages_set = {'Chinese', 'Japanese'}

# appending language_tuple elements to language languages.extend(languages_tuple)
print('New Language List:', languages)
# appending language_set elements to language languages.extend(languages_set)
print('Newer Languages List:', languages)

Output

New Languages List: ['French', 'Spanish', 'Portuguese']
Newer Languages List: ['French', 'Spanish', 'Portuguese', 'Japanese', 'Chinese']

Other Ways to Extend a List

You can also append all elements of an iterable to the list using:

1. the + operator

a = [1, 2]
b = [3, 4]

a += b # a = a + b
# Output: [1, 2, 3, 4] print('a =', a)

Output

a = [1, 2, 3, 4]

2. the list slicing syntax

a = [1, 2]
b = [3, 4]

a[len(a):] = b
# Output: [1, 2, 3, 4] print('a =', a)

Output

a = [1, 2, 3, 4]

Python extend() Vs append()

If you need to add an element to the end of a list, you can use the append() method.

a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)

# a1 = [1, 2, 3, 4]
a1.extend(b) 
print(a1)

# a2 = [1, 2, (3, 4)]
a2.append(b)
print(a2)

Output

[1, 2, 3, 4]
[1, 2, (3, 4)]

To learn more, visit list append() method.

Did you find this article helpful?