[python] Python error when trying to access list by index - "List indices must be integers, not str"

I have the following Python code :

currentPlayers = query.getPlayers()
    for player in currentPlayers:
        return str(player['name'])+" "+str(player['score'])

And I'm getting the following error:

TypeError: list indices must be integers, not str

I've been looking for an error close to mine, but not sure how to do it, never got that error. So yeah, how can I transform it to integers instead of string? I guess the problem comes from str(player['score']).

This question is related to python

The answer is


A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.


player['score'] is your problem. player is apparently a list which means that there is no 'score' element. Instead you would do something like:

name, score = player[0], player[1]
return name + ' ' + str(score)

Of course, you would have to know the list indices (those are the 0 and 1 in my example).

Something like player['score'] is allowed in python, but player would have to be a dict.

You can read more about both lists and dicts in the python documentation.


players is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:

name, score = player

(if the player list is always a constant length).

There's not much more advice we can give you without knowing what query is and how it works.

It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.