list.append() returns None
list.append() returns None in Python means append() changes the list in place and returns None. Assigning its result replaces your list with None.
How do I fix list.append() returns None?
In Python, list.append() changes the list in place and returns None. So tags = tags.append("new") replaces your list with None, and return items.append(x) returns None. Call items.append(x) on its own line and keep using items. The same applies to extend(), insert(), remove(), sort() and reverse().
- 1. Assigned append resultSearch for = something.append( or = something.sort(. Remove the assignment and call the method alone.
- 2. Returned append resultChange return items.append(x) to items.append(x) then return items on the next line.
- 3. Need a new list?Use items + [x], sorted(items) or list(reversed(items)), which return new lists instead of None.
What does list.append() returns None mean?
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(...).
Why does list.append() returns None happen?
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)).
Try it: fix this bug
easyget_sorted_scores([3, 1, 2]) returns None instead of [1, 2, 3].
def get_sorted_scores(scores):
return scores.sort()More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
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.