Python List extend() Method

Extends a list with the items from an iterable

Usage

The extend() method extends the list by appending all the items from the iterable to the end of the list. This method does not return anything; it modifies the list in place.

Syntax

list.extend(iterable)

Python list extend() method parameters
ParameterConditionDescription
iterableRequiredAny iterable (string, list, set, tuple, etc.)

Examples

# Add multiple items to a list
L = ['red', 'green', 'blue']
L.extend([1,2,3])
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]
# Add tuple items to a list
L = ['red', 'green', 'blue']
L.extend((1,2,3))
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]
# Add set items to a list
L = ['red', 'green', 'blue']
L.extend({1,2,3})
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]

extend() vs append()

extend() method treats its argument as an iterable object.

For example, when you pass a string (iterable object) as an argument, the method adds every character to a list instead of the string.

L = ['red', 'green', 'blue']
L.extend('red')
print(L)
# Prints ['red', 'green', 'blue', 'r', 'e', 'd']

Use append() method instead:

L = ['red', 'green', 'blue']
L.append('red')
print(L)
# Prints ['red', 'green', 'blue', 'red']

Equivalent Methods

Specifying a zero-length slice at the end is also equivalent to extend() method.

L = ['red', 'green', 'blue']
L[len(L):] = [1,2,3]
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]

Using concatenation operator + or the augmented assignment operator += on a list is equivalent to using extend().

# Concatenation operator
L = ['red', 'green', 'blue']
L = L + [1,2,3]
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]

# Augmented assignment operator
L = ['red', 'green', 'blue']
L += [1,2,3]
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]

Unlike concatenation operator, extend() doesn’t generate new objects. So, it’s usually faster than concatenation operator.