How to Fix: AttributeError: ‘NoneType’ object has no attribute ‘append’

3D illustration of a robot dropping a ball through a transparent ghost box, representing the NoneType object has no attribute append error.

This AttributeError NoneType append is a classic combination of two common problems: a NoneType error and a List method error.

It means: You are trying to use the .append() method, but the variable you’re using it on is None, not a list.

The Cause

This almost always happens when you call a function that was supposed to return a list, but it failed or had a code path that returned None instead.

Problem Code:

def get_user_scores(user_id):
    if user_id > 10:
        return [90, 85, 100]
    else:
        # This user has no scores, so we return nothing
        return None 

# 1. This works fine
high_scorer_list = get_user_scores(20)
high_scorer_list.append(99) # Appends to [90, 85, 100]

# 2. This crashes
low_scorer_list = get_user_scores(5) # This variable is now None
low_scorer_list.append(40)
# CRASH! AttributeError: 'NoneType' object has no attribute 'append'

The Fix: Always Return an Iterable (e.g., [])

The best fix is to make your function “safer.” A function that “gets a list” should always return a list, even if it’s an empty one.

Corrected Function:

def get_user_scores(user_id):
    if user_id > 10:
        return [90, 85, 100]
    else:
        # THE FIX: Return an empty list
        return []

Now, the code will run without crashing:

low_scorer_list = get_user_scores(5) # This variable is now []
low_scorer_list.append(40)
print(low_scorer_list) # Output: [40]

Similar Posts

Leave a Reply