TryBugHunt

list.sort() returns None

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

PythonPattern: Mutation and copying bugs

How do I fix list.sort() returns None?

To fix list.sort() returns None in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of assigning the result of sort(). Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does list.sort() returns None mean?

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.

Why does list.sort() returns None happen?

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.

Try it: fix this bug

easy

first_and_last("Mary Ann Smith") crashes: ValueError: too many values to unpack (expected 2, got 3).

def first_and_last(full_name):
    first, last = full_name.split(" ")
    return [first, last]
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, 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.