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

Proper Way to Shift Integer Into List Index Range

I need to retrieve the item at index i from list l. However, sometimes i falls outside of the range of the list index and throws an IndexError. I need to shift i to always be inside the range of the list index by leaps of len(l). The following code achieves just that.

l = ['a', 'b', 'c', 'd', 'e']

i = 6

while i >= len(l):
    i -= len(l)
while i < 0:
    i += len(l)

item = l[i] # item = 'b'

For my use case, i never falls more than len(l) out of range in either direction, so I’m able to shorten to this one liner by using if statements instead of while statements.

l = ['a', 'b', 'c', 'd', 'e']

i = -3

i = i-len(l) if i >= len(l) else i+len(l) if i < 0 else i

item = l[i] # item = 'c'

I’m thinking there must be some builtin function that achieves just this result, without a long, logical sentence. Is there a proper way to do this?

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 :

Seems like a perfect use case for the modulo operator.

item = l[i % len(l)]
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