What Are the Differences Between Python List append() and extend() Methods?

In this article, we're going to see what the Python list methods append() and extend() do, and how they differ from each other.

extend() Vs. append()

The following table shows the differences between the Python list extend() and append() methods:

append() extend()
Appends a single element (i.e. adds an element to the end of a list). Appends a list of elements (i.e. adds properties from an iterable to the end of a list).
Accepts any element as argument (such as a string, number, object, etc.). Accepts only an iterable as argument (such as a list, set, tuple, etc.).
Increases the length of the list by one. Increases the length of the list by the number of elements in its argument.
Adds element in a mutable way. Adds elements in a mutable way.
Quick Example:
x = [1, 2, 3]

x.append(3)
x.append([4, 5])

print (x)
# output: [1, 2, 3, 3, [4, 5]]
Quick Example:
x = [1, 2, 3]

x.extend([3])
x.extend([4, 5])

print (x)
# output: [1, 2, 3, 3, 4, 5]

How Does Python List append() Method Work?

Python's append() adds any element (such as a string, number, object, etc.) to the end of a list. It does so in a mutable way, and has the following syntax:

list.append(element)

For example:

x = ['a', 'b', 'c'];

x.append('d');

print (x)
# output: ['a', 'b', 'c', 'd']

Note that duplicate values are not overwritten. For example:

x = ['a', 'b', 'c'];

x.append('c');
x.append('d');

print (x)
# output: ['a', 'b', 'c', 'c', 'd']

Elements are appended as is. This means that if we append a list to another list, it won't unpack the elements of the list we're appending. For example:

x = ['a', 'b', 'c'];

x.append(['d', 'e']);

print (x)
# output: ['a', 'b', 'c', ['d', 'e']]

How Does Python List extend() Method Work?

Python's extend() adds properties from any iterable (such as a list, set, tuple, etc.) to the end of the current list. It does so in a mutable way, and has the following syntax:

list.extend(iterable)

For example:

x = ['a', 'b', 'c'];

x.extend(['d', 'e']);

print (x)
# output: ['a', 'b', 'c', 'd', 'e']

Note that duplicate values are added as is and are not overwritten. For example:

x = ['a', 'b', 'c'];

x.extend(['c', 'd']);

print (x)
# output: ['a', 'b', 'c', 'c', 'd']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.