Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2d List not returning
#1
Hey, Im trying to get this function to return a value like [x][y]
but it keeps giving me "line 54, in move
return [new_row][new_col]
IndexError: list index out of range."
(sorry for not knowing the correct terms for some of this stuff, im just starting out.)

player_row = 0
player_col = 0

def move(direction):
    new_col = player_col
    new_row = player_row
    if direction == "up":
        new_col += -1
    elif direction == "down":
        new_col += 1
    if direction == "left":
        new_row += -1
    elif direction == "right":
        new_row += 1
    return [new_row][new_col]
print(move("down"))
It gives me a [x] value if i remove either new_row or new_col from the return,
player_row = 0
player_col = 0

def move(direction):
    new_col = player_col
    new_row = player_row
    if direction == "up":
        new_col += -1
    elif direction == "down":
        new_col += 1
    if direction == "left":
        new_row += -1
    elif direction == "right":
        new_row += 1
    return [new_col]
print(move("down"))
and it will give me ([x],[y]) if i return "return [new_row], [new_col].
is there any way to get it to return [x][y] without the index error? Thanks.
Reply
#2
[x][y] is not a valid python object. [x] is one-element list as well as [y]. ([x], [y]) is two-element tuple, each element being one-element list.
maybe explain what you want to achieve
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Sep-22-2020, 05:03 PM)buran Wrote: [x][y] is not a valid python object. [x] is one-element list as well as [y]. ([x], [y]) is two-element tuple, each element being one-element list.
maybe explain what you want to achieve

Gotcha man, thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list.sort() returning None SmallCoder14 8 403 Mar-19-2024, 09:49 PM
Last Post: SmallCoder14
  returning a List of Lists nafshar 3 1,014 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Need help returning min() value of list? edwdas 3 2,009 Nov-10-2019, 09:43 PM
Last Post: snippsat
  API call returning list value of 'None' jimbone30 5 2,518 Jun-14-2019, 07:42 PM
Last Post: jimbone30

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020