Home > Mobile >  Python Move index in list with List index out of range
Python Move index in list with List index out of range

Time:07-23

I'm getting used to python. And some problems within the index in a list.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[a.index(3)   24])
//The result that I expect is: 7

OR:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[a.index(3)   -34])
//The result that I expect is: 9

Error: List index out of range

I don't know How do I make it right?. Is there any way I can get the expected result?

CodePudding user response:

So I understand what you are trying to do is when the index gets out of range you want to restart it from 0. For this you can use the modulus operator (%):

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[(a.index(3)   24) % 10])
print(a[(a.index(3)   -34) % 10])

I'm using % 10 because 10 is the length of the list. Modulo by 10 ensures that the resulting index is always between 0 and 9: You could also simply write:

print(a[(a.index(3)   24) % len(a)])

This way if you add more elements to the list, you do not have to change your code.

CodePudding user response:

You try to access an element outside of the array

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a[a.index(3)   24]

The lower part means - take element 4 (counting starts at 9) of the array (result 3) and add 24. (result 27). then you ask to take element 27 from a, which does not exist.

What makes you expect to get a 9 back?

  • Related