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?
>Solution :
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.