ComparisonComparisons

append() vs extend()

append() adds exactly one element to the end of a list, even if that element is itself a list, while extend() appends every element of the given collection in turn.

On this page

Side-by-side comparison

#

Example

#
Python
frontend = ["HTML"]
frontend.append("CSS")
frontend.extend(["JavaScript", "React"])

print(frontend)
Resultsaved result, you can check it
['HTML', 'CSS', 'JavaScript', 'React']

Definition and usage

#

Both methods modify the list in place and add new elements at its end. Both return None, so don’t assign their result back to the variable.

They differ in what counts as a single element. append(x) adds exactly what you pass as one new position, so a list passed to it lands at the end as a nested element. extend(collection) unpacks the given collection and appends each of its elements separately. The += operator on a list behaves like extend().

When you’re adding a single value, even if it’s itself a list or a tuple, use append(). When you want to append the contents of another collection element by element, use extend() or +=. Mixing them up is a common mistake: append() where extend() was meant creates a list with a nested list inside it.

Syntax

#
Syntax
my_list.append(element)
my_list.extend(iterable)

More examples

#
append() with a list nests it inside
Python
versions = ["1.0"]
versions.append(["1.1", "1.2"])
print(versions)

other = ["1.0"]
other.extend(["1.1", "1.2"])
print(other)
Resultsaved result, you can check it
['1.0', ['1.1', '1.2']]
['1.0', '1.1', '1.2']
extend() with a string adds its letters
Python
letters = ["a"]
letters.extend("bc")
print(letters)

letters.append("bc")
print(letters)
Resultsaved result, you can check it
['a', 'b', 'c']
['a', 'b', 'c', 'bc']

Good practices

#
  • Don’t write my_list = my_list.append(x) or my_list = my_list.extend(y). Both methods return None.
  • To add a single string as a whole, use append(), not extend().
  • If you don’t want to change the original, combine lists with the + operator: combined = a + b.

Related entries

#

Spotted a mistake or missing an example? Write to us.