Why am I getting list index out of range Error

Question:

When I go to run my code I get an list index out of range Error. Error is found when running this piece of code

for y in snakeLocation:
        print(snakeLocation[y])
        moveSquareSnake = snakeLocation[y]
        x[moveSquareSnake] = "S"

This is the rest of the code:

from tabulate import tabulate
import random

snakeDirection = "right"
extendSnake = "False"

fruitLocation = 0

score = 0

game = "Playing"

x = [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None]

boardData = [[x[0],x[1],x[2],x[3],x[4],x[5]],
             [x[6],x[7],x[8],x[9],x[10],x[11]],
             [x[12],x[13],x[14],x[15],x[16],x[17]],
             [x[18],x[19],x[20],x[21],x[22],x[23]],
             [x[24],x[25],x[26],x[27],x[28],x[29]],
             [x[30],x[31],x[32],x[33],x[34],x[35]]]

def fruitPlaceFunction():
    
    global fruitLocation

    fruitLocation = random.randint(0,35)
    for y in snakeLocation:
        if fruitLocation == snakeLocation[y]:
            fruitPlaceFunction()
    
    x[fruitLocation] = "F"


def gameLoop():

    global snakeLocation
    global extendSnake
    global game

    snakeLocation = [20,None]
    game = "Playing"

    if extendSnake == "True":
        extendSnake = "False"
        snakeLocation.append(fruitLocation)

    for y in snakeLocation:
        print(snakeLocation[y])
        moveSquareSnake = snakeLocation[y]
        x[moveSquareSnake] = "S"

        print("1")

    if x[fruitLocation] != "F":   
        fruitPlaceFunction()

    boardData = [[x[0],x[1],x[2],x[3],x[4],x[5]],
                 [x[6],x[7],x[8],x[9],x[10],x[11]],
                 [x[12],x[13],x[14],x[15],x[16],x[17]],
                 [x[18],x[19],x[20],x[21],x[22],x[23]],
                 [x[24],x[25],x[26],x[27],x[28],x[29]],
                 [x[30],x[31],x[32],x[33],x[34],x[35]]]

    print(tabulate(boardData,tablefmt='grid'))
    print("")

    print("Please enter "Up", "Down", "Left", or "Right" ")
    
    snakeDirection = (str(input("")))
    snakeDirection = snakeDirection.lower()

    while snakeDirection != "right" and snakeDirection != "left" and snakeDirection != "up" and snakeDirection != "down":
        print("Invalid Direction. Please enter "Up", "Down", "Left", or "Right" ")
        snakeDirection = (str(input("")))
        snakeDirection = snakeDirection.lower()

    for i in snakeLocation and i > 0:
        snakeLocation[i] = snakeLocation[i-1]

    if snakeDirection == "up":
        x[snakeLocation[-1]] = None
        snakeLocation[0] = snakeLocation[0] - 6

        if snakeLocation[0] < 0:
            game = "Over"
    
    elif snakeDirection == "down":
        x[snakeLocation[-1]] = None
        snakeLocation[0] = snakeLocation[0] + 6

        if snakeLocation[0] > 35:
            game = "Over" 

    elif snakeDirection == "left":
        x[snakeLocation[-1]] = None
        snakeLocation[0] = snakeLocation[0] - 1

        if snakeLocation[0] == -1 or snakeLocation[0] == 5 or snakeLocation[0] == 11 or snakeLocation[0] == 17 or snakeLocation[0] == 23 or snakeLocation[0] == 29:
            game = "Over"

    elif snakeDirection == "right":
        x[snakeLocation[-1]] = None
        snakeLocation[0] = snakeLocation[0] + 1

        if snakeLocation[0] == 6 or snakeLocation[0] == 12 or snakeLocation[0] == 18 or snakeLocation[0] == 24 or snakeLocation[0] == 30 or snakeLocation[0] == 36:
            game = "Over"   

    for i in snakeLocation:
        if snakeLocation[0] == snakeLocation[i]:
            game = "Over"

    if snakeLocation == fruitLocation:
        x[fruitLocation] = None
        extendSnake == "True"
        score = score + 1

while game == "Playing":
    gameLoop()
if game == "Over":
    print("Game Over")
    print("Score: {}".format(score))

I want it to just run and print out the value stored in the list

Asked By: Caleb Whyte

||

Answers:

snakeLocation = [20,None]

...

for y in snakeLocation:
    print(snakeLocation[y])

Unlike some other languages, iterating over a list in Python yields the values, not the indexes.

So on the first loop iteration, y is 20. And then you try to access snakeList[20], which is clearly out of range.

If you really did want to iterate over the indexes, use this:

for y in range(len(snakeLocation)):

.. although usually it’s the values you actually want, not the indexes, so you wouldn’t need this.

Answered By: John Gordon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.