1

So I have a list named "enemy_pos". Inside that, I have another 2 lists. When I try to change a number from one of that 2 lists it says "list index out of range"

Here is my code:

enemy_pos = [[0, -2, -12], [0, -1, -12]]
enemy_speed = 0.2

def move():
    for i in range(2):
        enemy_pos[[i][1]] -= enemy_speed
11
  • 1
    What do you think this mean enemy_pos[[i][1]]? Commented Mar 28, 2020 at 17:28
  • 3
    right syntax enemy_pos[i][1] Commented Mar 28, 2020 at 17:28
  • @AnkurJyotiPhukan enemy_pos[[i][1]] even this is right syntax.Example a=[1,2,3,4,5];a[[1,2,3][0]]--->2 Commented Mar 28, 2020 at 17:29
  • @Ch3steR really Commented Mar 28, 2020 at 17:31
  • 1
    @AnkurJyotiPhukan Not a problem. check here. You answered what OP needed, I was just saying it's correct syntax Commented Mar 28, 2020 at 17:35

2 Answers 2

2

The extra square bracket after enemy_pos in the last line is not required. It should be enemy_pos[i][1].

Sign up to request clarification or add additional context in comments.

Comments

2

The problem you're having is because enemy_pos[[i][1]] means Get the element from enemy_pos at index [i][1], where [i][1] means get the element at index 1 from the list [i]. However, [i] only has an element at index 0, which is why you're getting List index out of range.

The correct syntax for accessing elements from nested arrays is:

enemy_pos[i][1]

Loosely speaking, it means, get the list from enemy_post at index i, and from that list, get the element at index 1.

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.