Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Move index in list with List index out of range

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading