list.append()
Adds a single item to the end of a list. The list changes in place and the method itself gives back None.
list.append(x)append() puts one new item at the end of a list. The list grows by exactly one, whatever the item is: a number, a string, or even another list.
It is the most common way to build a list step by step, for example inside a for loop loop that collects results one at a time.
Two things surprise people. First, append() changes the list itself and returns None, so items = items.append(5) throws your list away. Second, appending a list puts that whole list inside as one item. To add several items one by one, use list.extend().
Parameters
| Parameter | What it is |
|---|---|
xrequired | The item to add. It can be any value, including another list, which is then stored as a single item. |
Return value
Nothing (None). The list is changed in place.
Examples
1Add an item to a shopping list
shopping = ["milk", "bread"]
shopping.append("eggs")
print(shopping)
print(len(shopping), "items")['milk', 'bread', 'eggs'] 3 items
2Build a list inside a loop
Start with an empty list and add one result on each round.
prices = [4.0, 10.0, 25.0]
with_tax = []
for p in prices:
with_tax.append(round(p * 1.2, 2))
print(with_tax)[4.8, 12.0, 30.0]
3append() vs extend()
Appending a list adds it as one single item. extend() adds its items one by one.
a = [1, 2]
a.append([3, 4])
print(a)
print(len(a))
b = [1, 2]
b.extend([3, 4])
print(b)
print(len(b))[1, 2, [3, 4]] 3 [1, 2, 3, 4] 4
a now has three items, and the last one is itself a list.
4Collect only the lines you want
log = ["OK login", "ERROR disk full", "OK save", "ERROR timeout"]
errors = []
for line in log:
if line.startswith("ERROR"):
errors.append(line[6:])
print(errors)['disk full', 'timeout']
Common mistakes
Assigning the result of append()
append() returns None. If you store that result, your variable no longer points to the list. Call it on its own line instead.
names = ["Ana", "Ben"]
names = names.append("Chloe")
print(names)
names = ["Ana", "Ben"]
names.append("Chloe")
print(names)None ['Ana', 'Ben', 'Chloe']
Trying to append several items at once
append() takes exactly one argument. nums.append(3, 4) raises a TypeError. Use extend([3, 4]), or call append() twice.
Questions people ask
What is the difference between append and extend in Python?
append(x) adds x as one item, even when x is a list. list.extend() loops over x and adds each of its items separately.
How do I add an item at the start of a list?
Use list.insert() with position 0: items.insert(0, "first"). For many additions at the front, collections.deque with appendleft() is faster.
Can I append to a list inside a dictionary?
Yes: groups["red"].append(5) changes the list stored under that key. If the key may be missing, use groups.setdefault("red", []).append(5).
Is append() fast?
Yes. Adding to the end of a list takes about the same time no matter how long the list is, so appending in a loop is fine even for large lists.