# Fix: list indices must be integers or slices

> TypeError: list indices must be integers or slices, not str. Read the word after ‘not’, then trace the list back to its source. Re-run on CPython 3.9-3.15.

- Canonical HTML: [https://unrust.dev/blog/list-indices-must-be-integers-or-slices](https://unrust.dev/blog/list-indices-must-be-integers-or-slices)
- Markdown representation: [https://unrust.dev/blog/list-indices-must-be-integers-or-slices/index.md](https://unrust.dev/blog/list-indices-must-be-integers-or-slices/index.md)

Published: 2026-11-22. By the Unrust team.

## What does "list indices must be integers or slices, not str" mean?

TypeError: list indices must be integers or slices, not str means you indexed a list with a string, as in users["name"]. The word after "not" names the type you used, and the usual cause is a list where you expected a dict, such as a JSON array: use users[0]["name"] or loop over it.

A list accepts an int, a bool (True is 1 and False is 0, because bool is a subclass of int), a slice such as nums[1:3], or any object with an __index__ method. Anything else raises this TypeError, including the string "1", which looks like a number but is not one.

The block below indexes one list with six wrong types and prints each message. We ran it on CPython 3.9.25, 3.10.22, 3.11.2, 3.11.18, 3.12.16, 3.13.18, 3.14.10 and 3.15.2, and the six lines are identical on all of them. Assigning to or deleting a list item gives the same message.

```python
nums = [10, 20, 30]
for index in ["1", 2.0, (1, 2), {"id": 1}, None, int]:
    try:
        nums[index]
    except TypeError as error:
        print(f"{index!r:<15}{error}")
# '1'            list indices must be integers or slices, not str
# 2.0            list indices must be integers or slices, not float
# (1, 2)         list indices must be integers or slices, not tuple
# {'id': 1}      list indices must be integers or slices, not dict
# None           list indices must be integers or slices, not NoneType
# <class 'int'>  list indices must be integers or slices, not type
```

## Which message did you get, and what fixes each one?

The word after "not" is the type of the index. A str usually means a loaded list treated like a dict, a float means a division, a tuple means grid[1, 2], a dict means a loop variable, NoneType means a function that returned nothing, and type means a class used where a number belongs.

The table gives the usual cause and fix, not every cause. A loop variable can be a str as easily as a dict, and input() always returns a str, so wrap it in int() before indexing. Check the line that built the index as well as the line that built the list.

Any other type shows its own name. nums[len] says not builtin_function_or_method, a function you forgot to call says not function, nums[[0, 2]] says not list (use [nums[i] for i in (0, 2)]), and an instance of your own Box class says not Box.

```text
Ends with     Example that raises it  Usual cause                 Fix
------------  ----------------------  --------------------------  ---------------------------
not str       users["name"]           a list used like a dict     users[0]["name"], or a loop
not float     nums[(lo + hi) / 2]     true division               use // instead of /
not tuple     grid[1, 2]              two indices in one bracket  grid[1][2]
not dict      records[record]         a loop variable is an item  use record directly
not NoneType  nums[last_index(nums)]  print instead of return     return the value
not type      nums[int]               a class, not a number       nums[int(text)]
```

## How do you fix it when the data comes from JSON?

A JSON array loads as a Python list and a JSON object loads as a dict, so data["name"] works only on an object. Print type(data).__name__ first. If it says list, use data[0]["name"] for one item or a loop for every item; if it says dict, find the key that holds the list.

The block below loads the same records in two shapes: a bare array, and an object that wraps the array under "results". Code written for one shape fails on the other, and a list that meets a string key fails with this message.

To look records up by name, build a dict once with a comprehension and index that. When two records share a name, the later one replaces the earlier one.

```python
import json

raw = '[{"name": "Ada", "role": "admin"}, {"name": "Bo", "role": "dev"}]'
users = json.loads(raw)
print(type(users).__name__)           # list
print(users[0]["name"])               # Ada
print([u["name"] for u in users])     # ['Ada', 'Bo']

by_name = {u["name"]: u for u in users}
print(by_name["Bo"]["role"])          # dev

wrapped = json.loads('{"results": ' + raw + "}")
print(type(wrapped).__name__)         # dict
print(wrapped["results"][0]["name"])  # Ada

print(users["name"])
# TypeError: list indices must be integers or slices, not str
```

## Which common calls return a list instead of a dict?

json.loads on an array returns a list, csv.reader yields a list per row, and re.findall returns a list, so a string key fails on all three with this message. A sqlite3 row from fetchone is a tuple by default and raises the tuple version. csv.DictReader rows and json.loads on an object are dicts, and input() returns a str.

With csv.reader the header is just rows[0], a list like any other, so rows[0]["name"] fails the same way; csv.DictReader reads the header and uses it as the keys.

A Match object from re.search is neither a list nor a dict, and it accepts m["year"] for a named group since Python 3.6. When nothing matches, re.search returns None, and indexing None raises a different error: 'NoneType' object is not subscriptable.

```text
Call                          Returns                Index it with
----------------------------  ---------------------  ---------------------------
json.loads on an array        list                   data[0]["name"], or a loop
json.loads on an object       dict                   data["name"]
csv.reader(f)                 a list per row         row[0]
csv.DictReader(f)             a dict per row         row["name"]
re.findall(p, s)              list of str or tuples  matches[0]
re.search(p, s)               a Match, or None       m["year"] for a named group
cursor.fetchone() in sqlite3  a tuple by default     row[0], or set row_factory
input()                       a str                  int(input())
```

## Why does a for loop give "not str" or "not dict"?

A for loop hands you each item, not its position. In for record in records, record is a dict, so records[record] ends in not dict; with a list of names the same mistake ends in not str. Use the item itself, or enumerate when you also need the position.

Predict first: which message does this code raise, and on which pass of the loop?

```python
records = [{"id": 1}, {"id": 2}]
for record in records:
    print(records[record])
```

### Answer and explanation

It raises TypeError: list indices must be integers or slices, not dict on the first pass, before anything prints. record is {'id': 1}, the first item of records, so records[record] indexes the list with a dict.

The loop already did the indexing for you. Use record["id"] directly, or loop over enumerate(records) when you also need the position.

```python
records = [{"id": 1}, {"id": 2}]
for record in records:
    print(record["id"])
# 1
# 2
for position, record in enumerate(records):
    print(position, record["id"])
# 0 1
# 1 2
```

## Why does it say "not float", and how do you fix a midpoint index?

Dividing two ints with / always gives a float in Python 3, even when the result is whole: (0 + 4) / 2 is 2.0. A list rejects 2.0 because a float has no __index__ method. Use floor division, (lo + hi) // 2, which returns an int.

This is a typical binary-search slip: mid = (lo + hi) / 2, then nums[mid]. The same mistake inside a slice, nums[:len(nums) / 2], raises the slice message listed near the end of this post.

Predict first: what are mid and its type, and what does the last line do?

```python
nums = [10, 20, 30, 40, 50]
lo, hi = 0, 4
mid = (lo + hi) / 2
print(nums[mid])
```

### Answer and explanation

mid is 2.0, a float. A list rejects it even though 2.0 equals 2, so the last line raises TypeError: list indices must be integers or slices, not float.

Floor division returns an int, so (lo + hi) // 2 is 2 and nums[2] is 30. int(mid) would also work, but it truncates silently: int(7 / 2) is 3.

```python
nums = [10, 20, 30, 40, 50]
lo, hi = 0, 4
mid = (lo + hi) // 2
print(mid, type(mid).__name__)  # 2 int
print(nums[mid])                # 30
print(7 / 2, 7 // 2)            # 3.5 3
```

## What do "not tuple", "not NoneType" and "not type" mean?

Each names the index's own type. A tuple means two indices in one bracket, as in grid[1, 2] on a list of lists: write grid[1][2]. NoneType means a function returned nothing, usually because it printed instead of returning, and type means you passed a class such as int where a number belongs.

Predict first: this code prints something before it fails. What does it print, and what is the message?

```python
nums = [10, 20, 30, 40, 50]

def last_index(items):
    print(len(items) - 1)

print(nums[last_index(nums)])
```

### Answer and explanation

It prints 4, then raises TypeError: list indices must be integers or slices, not NoneType. The 4 came from the print inside last_index; the function returned nothing, so the subscript received None.

A print is not a return value. Replace print with return, and nums[last_index(nums)] becomes nums[4].

```python
nums = [10, 20, 30, 40, 50]

def last_index(items):
    return len(items) - 1

print(nums[last_index(nums)])  # 50
```

## Why is it a TypeError and not an IndexError?

Python raises TypeError when the index has the wrong type and IndexError when the type is right but the position is outside the list. The data model documentation sets the same rule for __getitem__: an inappropriate type should raise TypeError, and an inappropriate value should raise IndexError for sequences or KeyError for mappings.

The wording gives a hint. In CPython 3.9 to 3.15 the TypeError says list indices, about the kind of index, and the IndexError says list index out of range, about its value. A dict raises KeyError for a missing key.

```text
Expression   What is wrong  Exception   Message
-----------  -------------  ----------  ------------------------------------------------
nums["1"]    the type       TypeError   list indices must be integers or slices, not str
nums[10]     the value      IndexError  list index out of range
prices["b"]  a missing key  KeyError    'b'
```

## How do you find where the wrong value came from?

Read the last line of the traceback, then check both sides of the brackets: print type(obj).__name__ for the object and repr(key) for the index. Next find the line that created the object and print what it received. Fix the shape there, not at the subscript.

Use repr for the index. print(key) shows 1 for both the int 1 and the string "1", while repr(key) shows '1' with quotes, which makes a str index visible. Our print debugging post shows more values that print the same.

```text
Step  Ask                                Check                          In the csv example
----  ---------------------------------  -----------------------------  -------------------
1     Which line failed?                 the last traceback frame       rows[1]["name"]
2     What is in front of the brackets?  print(type(rows[1]).__name__)  list
3     What is inside the brackets?       print(repr(key))               'name'
4     Where did the object come from?    the assignment above it        csv.reader(...)
5     What shape did the code assume?    fix it at that source          csv.DictReader(...)
```

## Fix the shape at the source, not the subscript

Patching the subscript, for example wrapping every index in int(), hides a mismatch that began earlier. Change the line that creates the value, and every later line can use it unchanged.

In the block below, csv.reader gives one list per row, so row["name"] fails. Switching to csv.DictReader at the source makes every later row["name"] work, and summing the qty column needs no other change.

```python
import csv
import io

text = "name,qty\nAda,2\nBo,5\n"
key = "name"

rows = list(csv.reader(io.StringIO(text)))
print(type(rows[1]).__name__)                # list
print(repr(key))                             # 'name'

rows = list(csv.DictReader(io.StringIO(text)))
print(rows[0][key])                          # Ada
print(sum(int(row["qty"]) for row in rows))  # 7
```

## Do tuples, strings and slices have their own messages?

Yes, and some of them changed between versions. A tuple uses the list wording, a str says string indices must be integers (with the type added from CPython 3.11), and a slice with a bad bound has its own sentence, reworded in 3.15. The table shows each message and the versions we ran.

A sqlite3 row from fetchone() is a tuple by default, so row["name"] raises the tuple message; setting conn.row_factory = sqlite3.Row makes it work. A JSON string indexed like an object raises the string message. Both repeat the list mistake: treating a sequence as a dict.

```text
Message                                                             CPython
------------------------------------------------------------------  ------------
tuple indices must be integers or slices, not str                   3.9 to 3.15
string indices must be integers                                     3.9 to 3.10
string indices must be integers, not 'str'                          3.11 to 3.15
slice indices must be integers or None or have an __index__ method  3.9 to 3.14
slice indices must be integers or have an __index__ method          3.15
```

## Quick answers about list index errors

Can you index a Python list with a string? No. A list is addressed by position, so nums["1"] raises TypeError; convert a numeric string with int("1") first. To find an item by its value, use nums.index(value), which returns the position or raises ValueError, or keep the data in a dict and look it up by key.

How do I look up a list of dicts by a key? Build a dict once with a comprehension, such as by_name = {u["name"]: u for u in users}, then use by_name["Ada"]. If two records share a name, the later one replaces the earlier one, so loop over the list instead when names can repeat or you need every match.

Why do some answers say "list indices must be integers, not str"? That is the CPython 3.4 and earlier wording. Version 3.5 added "or slices" (we checked Objects/listobject.c at tags v3.4.10 and v3.5.0), and the text has not changed through 3.15. The cause and the fix are the same, so those answers still apply.

Does assigning to or deleting a list item raise the same error? Yes. nums["a"] = 1 and del nums["a"] both raise TypeError: list indices must be integers or slices, not str, and nums[1.0] = 1 raises the not float version. We ran all three on every CPython from 3.9 to 3.15; only the index type matters, not the operation.

Why does nums[True] work when nums[1.0] does not? bool is a subclass of int, so True counts as 1 and False as 0, and nums[True] returns the second item. A float has no __index__ method, even when it equals a whole number. The boolean case is the quieter bug: a comparison used as an index returns an item instead of raising.

## References and next steps

[Python documentation: JSON decoding table (array to list, object to dict)](https://docs.python.org/3/library/json.html#json-to-py-table)
[Python documentation: object.__getitem__ (TypeError, IndexError, KeyError)](https://docs.python.org/3/reference/datamodel.html#object.__getitem__)
[Python documentation: csv.reader and csv.DictReader](https://docs.python.org/3/library/csv.html)
[Unrust blog: Python debugging exercises: 10 bugs to fix](https://unrust.dev/blog/python-debugging-exercises)
[Unrust blog: Print debugging: 7 ways your output lies](https://unrust.dev/blog/print-debugging)
[Unrust: Python Debugging Practice for Developers](https://unrust.dev/languages/python/debugging)
[Unrust: Python Coding Practice for Developers](https://unrust.dev/languages/python)
[Unrust guide: What is code tracing?](https://unrust.dev/guides/code-tracing)
[Unrust blog: Separate the first symptom from the root cause in service logs](https://unrust.dev/blog/trace-first-symptom-vs-root-cause-in-logs)
[Unrust blog: Idiomatic Python: 10 patterns with examples](https://unrust.dev/blog/idiomatic-python-examples)
[Unrust blog: Python list comprehensions: examples and traps](https://unrust.dev/blog/python-list-comprehensions)

[How do you debug code without AI?](https://unrust.dev/guides/debugging-without-ai/index.md)

## See how you debug with AI off

Take Unrust's free diagnostic with AI and hints closed. After a warm-up you get a few short drills that include tracing and debugging, then a per-skill read. It takes about 14 minutes, and you do not need an account for your first read.

[Take the free diagnostic](https://unrust.dev/diagnostic/index.md)
