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.

The 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

Example: Add multiple items to a list

L = ['red', 'green', 'blue']
L.extend([1,2,3])
print(L)    # ['red', 'green', 'blue', 1, 2, 3]

Example: Add tuple items to a list

L = ['red', 'green', 'blue']
L.extend((1,2,3))
print(L)    # ['red', 'green', 'blue', 1, 2, 3]

Example: Add set items to a list

L = ['red', 'green', 'blue']
L.extend({1,2,3})
print(L)  # ['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.

Example:

extend() adds every character instead of just the string

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

Use append() method instead:

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

Equivalent Methods

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

Example: extend() is equivalent to zero-length slice at the end

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

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

Example: + or += is equivalent to extend()

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

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