user3666755
user3666755

Reputation: 45

Graphing program cant get x,y from list

I am making a sort of graph for a text based game and I have some code for a part of the graphing. I want to add the places the player has been to a list of x, y coordinates so I can draw it later.

objects = {"Player":[2,2]}
clearedSpaces = []

def changePos(name, newx, newy):
    objects[name][0] += newx
    objects[name][1] += newy
    global clearedSpaces
    clearedSpaces.append([objects[name][0],objects[name][1]])

#####Each of these makes the player go up one space#####
changePos("Player",1,0)
changePos("Player",1,0)
changePos("Player",1,0)
changePos("Player",1,0)


print clearedSpaces
for space in clearedSpaces:

    ########Here is where the problem seems to occur########
    print(clearedSpaces[space][0])
    print(clearedSpaces[space][1])
    print space

I put a comment above where the problem seems to be. also heres the error I get:

Traceback (most recent call last): File "", line 19, in TypeError: list indices must be integers, not list

Upvotes: 0

Views: 23

Answers (1)

abarnert
abarnert

Reputation: 365975

clearedSpaces is a list of lists of integers.

So for space in clearedSpaces means that each space is a list of integers.

So clearedSpaces[space] is trying to use a list as an index. Hence the TypeError: list indices must be integers, not list.


What you almost certainly wanted was just space itself:

for space in clearedSpaces:
    print(space[0])
    print(space[1])
    print(space)

If you really do need the index for some reason, use enumerate:

for i, space in enumerate(clearedSpaces):
    print(clearedSpaces[i][0])

But in this example, that isn't useful, because you already have space, which is the same thing as clearedSpaces[i] (but more readable).

Upvotes: 2

Related Questions