BugHunt

list.sort() returns None

sort() sorts in place and gives back None. Assigning its result throws the list away.

PythonMutation and copying bugs

What it means

Python marks methods that mutate by returning None. list.sort(), list.reverse() and list.append() all do this, and the None return is a deliberate signal that the object changed rather than a new one being produced.

Common causes

1. Assigning the result of sort()

The list is sorted correctly, then replaced with None.

Breaks

names = names.sort()

Works

names.sort()            # in place
# or
names = sorted(names)   # new list

2. Chaining off a mutating method

The chain continues on None, so the next call fails.

Breaks

first = names.sort()[0]

Works

first = sorted(names)[0]

How to find it in your own code

Remember the pair: sort/sorted, reverse/reversed. The bare verb mutates and returns None; the -ed form returns a new list. If a variable mysteriously becomes None, check whether the last thing assigned to it was a mutating method.

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.

Other common errors