Join our newsletter for the latest updates.

Python List extend()

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

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

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

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

# appending language1 elements to language
language.extend(language1)

print('Language List:', language)

Output

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

Example 2: Add Elements of Tuple and Set to List

# language list
language = ['French']

# language tuple
language_tuple = ('Spanish', 'Portuguese')

# language set
language_set = {'Chinese', 'Japanese'}

# appending language_tuple elements to language
language.extend(language_tuple)

print('New Language List:', language)

# appending language_set elements to language
language.extend(language_set)

print('Newer Language List:', language)

Output

New Language List: ['French', 'Spanish', 'Portuguese']
Newer Language 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.