Coding

Append in Python: list.append() Examples, extend and insert

To append in Python, call my_list.append(item): it adds one item to the end of the list, changes the list in place, and returns None. To add several items at once use extend(), and to add at a specific position use insert().

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)

Example output:

['apple', 'banana', 'cherry']

What list.append() does

The Python tutorial describes it as: "Add an item to the end of the list. Similar to a[len(a):] = [x]." It takes exactly one argument. Whatever you pass becomes a single new element, whether it is a number, a string, another list or an object of your own.

Because append() modifies the list that already exists, every other variable that points at the same list sees the change. Appending to a list is also cheap: the tutorial says "appends and pops from the end of list are fast".

Why does my list become None after append?

This is the most common append mistake. append() returns None, so assigning its result throws your list away:

numbers = [1, 2, 3]
numbers = numbers.append(4)
print(numbers)

Example output:

None

The tutorial explains the rule: methods like insert, remove or sort that only modify the list "return the default None. This is a design principle for all mutable data structures in Python." The standard library reference states it more generally: methods that change a collection in place and don't return a specific item never return the collection itself. So chaining such as numbers.append(4).append(5) fails too, with AttributeError: 'NoneType' object has no attribute 'append'. Call append() as a statement and keep using the original variable:

numbers = [1, 2, 3]
numbers.append(4)
numbers.append(5)
print(numbers)

Example output:

[1, 2, 3, 4, 5]

Append vs extend: adding one item or many

extend() takes an iterable and adds each of its elements. The tutorial calls it "Extend the list by appending all the items from the iterable." The difference shows up as soon as you pass a list:

a = [1, 2]
a.append([3, 4])
print(a)

b = [1, 2]
b.extend([3, 4])
print(b)

Example output:

[1, 2, [3, 4]]
[1, 2, 3, 4]

The first list now holds three elements, the last of which is a nested list. The second holds four numbers. Choose append() when the thing you have is one item, and extend() when you have a collection whose members should go into the list individually.

Watch out when you extend with a string. A string is an iterable of characters, so each character becomes its own element:

words = ["hi"]
words.extend("abc")
print(words)

Example output:

['hi', 'a', 'b', 'c']

If you wanted the whole string as one element, use words.append("abc"). The += operator on a list behaves like extend(): the standard library reference says it extends the list with the contents of the right-hand side. That means items += "abc" also adds three characters, not one string.

Insert at a specific position

list.insert(index, value) places a value before the element currently at index. The tutorial notes that a.insert(0, x) inserts at the front of the list and a.insert(len(a), x) is equivalent to a.append(x).

queue = ["b", "c"]
queue.insert(0, "a")
print(queue)

Example output:

['a', 'b', 'c']

Inserting at the front is slow on long lists, because all the other elements have to be shifted by one. The same applies to popping from the front. For first-in, first-out queues the tutorial recommends collections.deque, "designed to have fast appends and pops from both ends":

from collections import deque

queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
print(queue.popleft())

Example output:

Eric

Append in a loop

The usual pattern is to start with an empty list and append inside a loop, often with a condition:

squares = []
for n in range(1, 6):
    if n % 2 == 1:
        squares.append(n * n)
print(squares)

Example output:

[1, 9, 25]

When the loop only transforms or filters items like this, a list comprehension says the same thing in one line: [n * n for n in range(1, 6) if n % 2 == 1]. See Python list comprehension for the syntax. Keep the explicit loop with append() when the body does more than build one value, for example when it logs, handles errors or appends to several lists.

Append a dictionary, a list or a tuple

Since append() stores whatever you give it as a single element, it works for building lists of records:

users = []
users.append({"name": "Ana", "age": 31})
users.append({"name": "Ben", "age": 27})
print(users[1]["name"])

pairs = []
pairs.append((1, "one"))
pairs.append((2, "two"))
print(pairs)

Example output:

Ben
[(1, 'one'), (2, 'two')]

Tuples are a good fit for small fixed records like the pairs above; see Python tuples explained for how they differ from lists. After building a list, counting items in a list covers len() and count().

The shared-list trap: appending to [[]] * 3

Appending can look broken when a list contains copies of the same inner list. The standard library reference warns about this when it explains the * operator: items in the sequence "are not copied; they are referenced multiple times." Its example:

lists = [[]] * 3
lists[0].append(3)
print(lists)

Example output:

[[3], [3], [3]]

All three slots refer to one inner list, so an append through any of them shows up in all of them. The reference suggests building distinct lists instead:

lists = [[] for _ in range(3)]
lists[0].append(3)
print(lists)

Example output:

[[3], [], []]

A related surprise is appending a list to itself or appending a list you later keep changing. The list holds a reference, not a snapshot, so later changes to that object appear inside the outer list. If you need an independent copy, append inner.copy() or list(inner).

Common errors

  • AttributeError: 'tuple' object has no attribute 'append' (or 'str'): tuples and strings are immutable and have no append(). Create a new one with +, or convert to a list first with list(my_tuple).
  • TypeError: list.append() takes exactly one argument (2 given): you passed two arguments, such as items.append(1, 2). Wrap them in one container, items.append((1, 2)), or use extend([1, 2]) to add both separately. The exact wording of the message differs between Python versions.
  • AttributeError: 'NoneType' object has no attribute 'append': the variable is None, usually because an earlier line assigned the result of an in-place method such as sort() or append() to it. Fix the assignment, not the append.
  • Appending while looping over the same list: adding to a list you are iterating over can keep the loop running longer than expected, because the new items are visited too. Iterate over a copy (for x in items[:]:) or collect new items in a separate list and extend afterwards.

Which method should I use?

GoalUseResult for [1, 2] and [3, 4]
Add one item at the endappend(x)[1, 2, [3, 4]] when x is the list
Add every item of an iterableextend(it)[1, 2, 3, 4]
Add at position iinsert(i, x)insert(0, 9) gives [9, 1, 2]
Make a new combined lista + b[1, 2, 3, 4], originals unchanged

The first three change the list in place and return None. The + operator builds a new list, which is the right choice when you must not modify the original.

Frequently asked questions

What does append return in Python?
list.append() returns None. It changes the list in place and does not hand back the list, so writing items = items.append(4) replaces your list with None. Call items.append(4) on its own line and keep using items.
What is the difference between append and extend in Python?
append adds its argument as one single item at the end of the list. extend takes an iterable and adds each of its elements separately. [1, 2].append([3, 4]) gives [1, 2, [3, 4]], while [1, 2].extend([3, 4]) gives [1, 2, 3, 4].
Can you append to a tuple or a string in Python?
No. Tuples and strings are immutable and have no append method, so calling it raises AttributeError. Build a new tuple or string with + instead, or collect the pieces in a list, append to that, and convert at the end.
How do I append to the beginning of a list?
Use list.insert(0, value). It shifts every other element one place to the right, so it is slow on long lists. If you add to the front often, collections.deque with appendleft() is designed for that.

Sources