Jože Strožer
Jože Strožer

Reputation: 793

List Index Out Of Range In For Loop

im trying to put if statements in a for loop. The conditions are read from an arrays. (making a game in pygame..)

This is the field_array array.

field_array = [(100, 100), (150, 100), (200, 100)]

Here is my if statements in a for loop.

for x in field_array:
    if player_new_coord[0] >= field_array[num][0] and player_new_coord[0] <= field_array[num][0]+50:
        if player_new_coord[1]+player_height >= field_array[num][1] and player_new_coord[1] <= field_array[num][1]+50:
            print("farm")
    num += 1

I get the following error.

2DFarmingSimulator.py", line 81, in Main

if player_new_coord[0] >= field_array[num][0] and player_new_coord[0] <= field_array[num][0]+50:
IndexError: list index out of range
Press any key to continue . . .

Thank you for your time and help.

Upvotes: 1

Views: 81

Answers (3)

Basya
Basya

Reputation: 1485

Without the whole code, I don't know how num is defined or initialized. It clearly has the wrong value when you use it as an index into the list.

But....you don't need an index into the list!

You are already iterating through the loop. x is the current item.

So this should work (to run the code I created the values which you use but do not define in your code samples, assigning them values I picked out of the air. This code runs.)

field_array = [(100, 100), (150, 100), (200, 100)]

player_new_coord = [130,120]
player_height = 119

for x in field_array:
    if player_new_coord[0] >= x[0] and player_new_coord[0] <= x[0]+50:
        if player_new_coord[1]+player_height >= x[1] and player_new_coord[1] <= x[1]+50:
            print("farm")

Of course, you will need to remove the lines defining player_new_coord and player_height and use the values you need for them.

Upvotes: 1

David Duffrin
David Duffrin

Reputation: 87

In your code snippet, x is being assigned (100, 100), (150, 100), (200, 100), however this is not used. Also, we cannot see what num is set to, so I assume that you mean to initialize num to the first index and increment on every loop.

The following code snippet will assign x to the correct indices and the for loop will take care of incrementing num for you after every iteration.

for num in range(len(field_array)):
    if player_new_coord[0] >= field_array[num][0] and player_new_coord[0] <= field_array[num][0]+50:
        if player_new_coord[1]+player_height >= field_array[num][1] and player_new_coord[1] <= field_array[num][1]+50:
            print("farm")

Upvotes: 0

binu.py
binu.py

Reputation: 1216

num should be initialized before it is used as an index of the array in the if statement. As num is not present it is giving index error. initialize num to something or 0

Upvotes: 0

Related Questions