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.
Side-by-side comparison
#What it adds
- list.append()
- Exactly one element
- list.extend()
- Every element of the collection, one after another
A list passed as the argument
- list.append()
- Lands at the end as one nested element
- list.extend()
- Gets unpacked: each element separately
Change in the list’s length
- list.extend()
- the number of elements in the collection
A string as the argument
- list.append()
- Adds the whole string as one element
- list.extend()
- Adds each character of the string separately
Equivalent operator
- list.append()
- None
Typical use
- list.append()
- Adding a single value, e.g. a computed result
- list.extend()
- Combining two lists into one
Example
#frontend = ["HTML"]
frontend.append("CSS")
frontend.extend(["JavaScript", "React"])
print(frontend)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
#my_list.append(element)
my_list.extend(iterable)More examples
#versions = ["1.0"]
versions.append(["1.1", "1.2"])
print(versions)
other = ["1.0"]
other.extend(["1.1", "1.2"])
print(other)letters = ["a"]
letters.extend("bc")
print(letters)
letters.append("bc")
print(letters)Good practices
#- Don’t write
my_list = my_list.append(x)ormy_list = my_list.extend(y). Both methods returnNone. - To add a single string as a whole, use
append(), notextend(). - 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.