Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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']).

like image 492
Tom Jenkins Avatar asked Jan 07 '13 15:01

Tom Jenkins


People also ask

How do I fix list indices must be integers or slices not str in Python?

The Python "TypeError: list indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a list at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_list[int(my_str)] .

How do you fix TypeError list indices must be integers or slices not list?

This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function.


2 Answers

Were you expecting player to be a dict rather than a list?

>>> player=[1,2,3] >>> player["score"] Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str >>> player={'score':1, 'age': 2, "foo":3} >>> player['score'] 1 
like image 158
Spacedman Avatar answered Sep 19 '22 11:09

Spacedman


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.

like image 37
ken.ganong Avatar answered Sep 20 '22 11:09

ken.ganong