list.append() returns None
append() changes the list in place and returns None. Assigning its result replaces your list with None.
What it means
Methods that modify a list (append, extend, insert, remove, sort, reverse) return None on purpose, as a signal that they changed the original rather than building a new one. The bug is always the same: x = x.append(...) or return x.append(...).
Common causes
1. Assigning the result of append
The append happens, then the list is thrown away.
Breaks
tags = tags.append("new")Works
tags.append("new")2. Returning the result of append
The function returns None to its caller.
Breaks
def add(items, x):
return items.append(x)Works
def add(items, x):
items.append(x)
return items3. Chaining list methods
The second call runs on None.
Breaks
items.append(3).sort()Works
items.append(3)
items.sort()How to find it in your own code
Call in-place methods on their own line. If you want a new list instead of changing the old one, use an expression that builds one: items + [x], sorted(items), list(reversed(items)).
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.