Quick answer: You used square brackets on a value that is None. Something you expected to be a list, tuple or dict is None: a function that never reached a return, the result of an in-place method such as list.sort() or rect.move_ip(), a failed lookup such as dict.get() or re.match(), a JSON null, or a Pygame call that returns None when there is nothing to report. Find the value to the left of the failing bracket, trace where it was assigned, then either fix that source or check for None before indexing.

The traceback points at a line like tile = level[1][1] or x = hit[0] and says 'NoneType' object is not subscriptable. The line itself is usually fine. The mistake is earlier, at the place where the variable was given None. This guide shows how to read which value is None from the traceback, lists the sources of None that turn up in Pygame projects (each one checked against pygame 2.6), and gives the fix for each.

The exact error

Traceback (most recent call last):
  File "game.py", line 8, in <module>
    start_tile = level[1][1]
                 ~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

The wording is the same in every current Python 3 version. The marker line under the code (~~~~~^^^) appears from Python 3.11; on 3.10 and earlier you get only the source line.

Close relatives, all caused by the same unexpected None:

TypeError: 'NoneType' object does not support item assignment    # level[0] = row
TypeError: 'NoneType' object does not support item deletion      # del level[0]
TypeError: cannot unpack non-iterable NoneType object            # x, y = find_spawn(level)
AttributeError: 'NoneType' object has no attribute 'rect'        # hit.rect

The last one has its own guide: How to Fix “AttributeError: ‘NoneType’ object has no attribute” in Pygame.

What it means

“Subscripting” is the square-bracket operation: a[0], a["key"], a[1:3]. Lists, tuples, strings, dicts, pygame.Rect and pygame.math.Vector2 support it. None does not. None is the single value of the type NoneType, which is why the message says 'NoneType' and never names your variable.

None gets into a variable in three ways: a function returned it explicitly, a function ended without returning anything (Python returns None for you), or data you loaded contained it. Every cause below is one of those.

How to find which value is None

On Python 3.11 or later, read the marker line. The ~ characters underline the expression that was None and the ^ characters underline the bracket that failed:

    x = save["player"]["checkpoint"]["x"]
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
TypeError: 'NoneType' object is not subscriptable

Here save["player"]["checkpoint"] is None, and ["x"] is the failing subscript. save and save["player"] are fine, or the markers would stop sooner.

When the value to the left of the bracket is a call, as in find_spawn(level)[0], the ~ characters underline the whole call. That function returned None, and you can go straight to its return statements.

On older Python, or when the marker is missing, split the line and print each step:

player = save["player"]
print("player:", player)
checkpoint = player["checkpoint"]
print("checkpoint:", checkpoint)
x = checkpoint["x"]

Once you know which name holds None, search backwards for its most recent assignment. That assignment, and the function it calls, is where the fix goes. Python’s built-in debugger does the same job interactively: put breakpoint() on the line before the failure and type the variable names at the (Pdb) prompt.

The assignment can be a long way from the crash. A None stored in a list or on an attribute at load time is not indexed until the player reaches the level that uses it. When the name was filled in by a loader, check what the loader put there before you look at the line in the traceback.

Where the None came from

SourceExampleFix
Function with no returnlevel = load_level(path) where the loader builds a list and stopsReturn the value
return on only some pathsfind_spawn(level) when the level has no spawn tileReturn or raise on every path
In-place method assigned to a variableranked = scores.sort(), rect = rect.move_ip(5, 0)Do not assign, or use the version that returns a value
Lookup that found nothingsave.get("inventory"), re.match(...), os.environ.get(...)Supply a default or check the result
JSON null"checkpoint": null in a save fileTreat None as a valid stored value
Pygame call with nothing to reportmask.overlap() with no overlap, mixer.get_init() before initCheck for None first

Fix 1: the function that forgot to return

The most common version in a game is a loader that builds its result and never hands it back:

def load_level(path):
    rows = []
    with open(path) as f:
        for line in f:
            rows.append(list(line.rstrip("\n")))

level = load_level("levels/01.txt")
start_tile = level[1][1]        # TypeError: level is None

A function that reaches its end without a return statement returns None. Add the return:

def load_level(path):
    rows = []
    with open(path) as f:
        for line in f:
            rows.append(list(line.rstrip("\n")))
    return rows

A close cousin is the function that prints its result where it should return it. print(rows) shows the correct list in the console, which makes the function look finished, and the caller still receives None.

The second version returns a value on one path and falls off the end on another:

def find_spawn(level):
    for y, row in enumerate(level):
        for x, tile in enumerate(row):
            if tile == "P":
                return (x, y)

spawn = find_spawn(level)
player.rect.x = spawn[0] * TILE     # fails on a level with no "P"

Decide what a missing spawn means. If it is a broken level file, fail loudly at the cause with a message that says so:

spawn = find_spawn(level)
if spawn is None:
    raise ValueError("level has no 'P' spawn tile")
player.rect.x = spawn[0] * TILE

If it is a normal situation, write return None explicitly at the end of the function so the next reader sees it, and make every caller handle it.

Fix 2: in-place methods return None

Python and Pygame both follow a convention: a method that modifies an object in place returns None, so that you cannot mistake it for one that builds a new object. Assigning the result throws your data away:

ranked = scores.sort(key=lambda entry: entry[1], reverse=True)
best = ranked[0]                 # TypeError: ranked is None

deck = random.shuffle(cards)
hand = deck[:5]                  # TypeError

rect = rect.move_ip(5, 0)
left = rect[0]                   # TypeError

Either call the method on its own line and keep using the original variable, or use the counterpart that returns a new object:

Returns None (changes the object)Returns a new value
items.sort()sorted(items)
items.reverse()list(reversed(items)) or items[::-1]
random.shuffle(items)random.sample(items, k=len(items))
items.append(x), items.extend(more), items.insert(i, x)items + [x], items + more
items.remove(x), items.clear()A list comprehension that filters
settings.update(other), seen.add(x)settings | other (Python 3.9+), seen | {x}
rect.move_ip(), rect.inflate_ip(), rect.clamp_ip(), rect.union_ip()rect.move(), rect.inflate(), rect.clamp(), rect.union()
vec.normalize_ip(), vec.rotate_ip(), vec.scale_to_length()vec.normalize(), vec.rotate()

In Pygame the suffix _ip means “in place”, and every _ip method on Rect and Vector2 returns None. The fixed versions of the three lines above:

ranked = sorted(scores, key=lambda entry: entry[1], reverse=True)
best = ranked[0]

random.shuffle(cards)
hand = cards[:5]

rect = rect.move(5, 0)           # or: rect.move_ip(5, 0) with no assignment
left = rect[0]

Your own methods follow the same convention whether you planned it or not. A shuffle_deck(cards) helper that shuffles the list it was given and has no return hands None to anyone who writes deck = shuffle_deck(cards). Pick one behavior per function, change the argument or return a new value, and name it accordingly.

Group and sprite methods (group.add(), group.remove(), sprite.kill()) and pygame.display.flip() return None as well. Surface.blit() and Surface.fill() are different: they return the affected Rect.

Fix 3: lookups that found nothing, and JSON null

dict.get(key) returns None when the key is missing. That is its purpose, and it moves the failure from the lookup to the next line:

first_item = save.get("inventory")[0]     # TypeError when "inventory" is absent

Pass a default of the right type, or use save["inventory"] when the key is required and you want a KeyError that names it:

inventory = save.get("inventory", [])
first_item = inventory[0] if inventory else None

A default does not help when the key is present with the value null. json.load() turns JSON null into None, and save.get("checkpoint", {}) returns that None, since the key exists. Use or to cover both cases:

checkpoint = save.get("checkpoint") or {"x": 0, "y": 0}
x = checkpoint["x"]

re.match(), re.search() and re.fullmatch() return None when the text does not match. A settings parser hits this on the first value it did not expect:

def parse_resolution(text, default=(1280, 720)):
    m = re.match(r"(\d+)x(\d+)$", text.strip())
    if m is None:
        return default
    return int(m[1]), int(m[2])

Without the check, parse_resolution("fullscreen") fails at m[1]. os.environ.get("NAME") behaves the same way for an unset environment variable.

Fix 4: Pygame functions that return None

Several Pygame calls return None to mean “nothing” or “not initialized”. These are the ones whose normal result is something you would index:

CallNormal resultReturns None when
mask.overlap(other, offset)(x, y) of the first overlapping pixelThe masks do not overlap
pygame.sprite.collide_mask(a, b)(x, y) point of collisionThe sprites do not collide
rect.collidedict(d, True)(key, value) of the first hitNothing in the dict collides
pygame.mixer.get_init()(frequency, format, channels)The mixer is not initialized
surface.get_colorkey()RGBA colorNo colorkey is set
pygame.font.match_font(name)Path to the font file (a string)No such system font is installed

The pattern is the same for all of them: store the result, test it, then index.

offset = (enemy.rect.x - player.rect.x, enemy.rect.y - player.rect.y)
point = player.mask.overlap(enemy.mask, offset)
if point is not None:
    spawn_spark(player.rect.x + point[0], player.rect.y + point[1])

Write is not None instead of a bare if point: when the value can legitimately be falsy. An overlap at (0, 0) is a non-empty tuple and therefore true, but a count of 0, an empty list or an empty string would be skipped by a truthiness test.

Other Pygame calls return None in place of an object: pygame.sprite.spritecollideany() with no collision, pygame.display.get_surface() before set_mode(), and pygame.mixer.find_channel() when every channel is busy. Using those results unchecked gives the AttributeError variant, since you call a method on them. Note that pygame.sprite.spritecollide() and groupcollide() never return None: with no collisions they return an empty list and an empty dict, and indexing [0] on the empty list raises IndexError.

How to confirm the fix, and catch it before running

Reproduce the case that produced the None: the level without a spawn tile, the save file without the key, the frame with no collision. A fix tested only on the path that already worked proves nothing.

When a function may return None, say so in its signature. A type checker then flags every caller that indexes the result without a check, before the game runs:

def find_spawn(level: list[list[str]]) -> tuple[int, int] | None:
    for y, row in enumerate(level):
        for x, tile in enumerate(row):
            if tile == "P":
                return (x, y)
    return None

With that annotation (Python 3.10 or later for the | syntax), find_spawn(level)[0] is reported by mypy as Value of type "tuple[int, int] | None" is not indexable and by Pyright as Object of type "None" is not subscriptable. Both also know that re.match() can return None.

At the edges of your program (save files, level files, config), validate once after loading and raise an error that names the file and the field. A message such as save.json: "checkpoint" is null costs one line and replaces a traceback that points at an innocent line fifty calls later.

Catching it on players’ machines

This error ships most often through data you do not control: an old save file missing a key, a hand-edited config, a level from a mod. Those cases never occur on your machine. The Bugnet Pygame SDK (pip install bugnet-sdk) installs an exception hook when you call bugnet_sdk.init(api_key). An uncaught TypeError is filed with its traceback, the platform, OS version and game version, and the upload is flushed before Python exits. On Python 3.11 and later the traceback includes the marker line, so the report shows which expression was None.

Know the limits. The report holds the traceback and the last lines the game printed. It does not hold the player’s save file or the values of your variables, so print the file name and key you are loading and that line travels with the report. Reports with the same title stack into one entry with an occurrence count, and the title here is the message 'NoneType' object is not subscriptable, which is identical for every instance of this error in your code. Check the traceback on each occurrence before treating the entry as one bug, or catch the exception at the loader and call bugnet_sdk.report_error(message, stack) with a message that names the file. The SDK docs list the calls.

Frequently asked questions

What does “TypeError: 'NoneType' object is not subscriptable” mean?

You used square brackets on a value that is None. A variable you expected to hold a list, tuple or dict holds None, usually because the function that produced it returned nothing or a lookup found nothing.

How do I find which variable is None?

On Python 3.11 and later, the marker line under the code underlines the expression that was None with ~ characters and the failing bracket with ^ characters. On older versions, split the line into one subscript per statement and print each intermediate value.

Why does list.sort() return None?

Methods that change an object in place return None by convention, so they cannot be mistaken for functions that build a new object. Call items.sort() on its own line and keep using items, or use sorted(items) when you want a new list. The same applies to random.shuffle(), list.append() and Pygame methods ending in _ip.

Which Pygame functions return None?

Mask.overlap() and pygame.sprite.collide_mask() return None when nothing overlaps, Rect.collidedict() when nothing collides, pygame.mixer.get_init() when the mixer is not initialized and Surface.get_colorkey() when no colorkey is set. Every in-place method ending in _ip, such as Rect.move_ip(), also returns None.

What is the difference between “not subscriptable” and “has no attribute” for NoneType?

The cause is the same, an unexpected None, and only the operation differs. Square brackets on None raise the TypeError, and a dot access such as hit.rect on None raises the AttributeError. Both are fixed at the place where the None was produced.

The traceback line is where None was used, and the bug is where None was produced. Find the value to the left of the failing bracket and trace it back to a missing return, an in-place method or a lookup that found nothing.