1

I want an array to loop when the code throws the IndexError. Here is the Example:

a = [1, 2, 3, 4, 5]

a[x] -> output
0 -> 1
1 -> 2
...
4 -> 5
after except IndexError
5 -> 1
6 -> 2
...
9 -> 5
10 -> IndexError (Should be 1)

My code works but when pos > 9 it still throws the IndexError.

pos = 5
try:
    a = [1, 2, 3, 4, 5]
    print(a[pos])
except IndexError:
    print(a[pos - len(a)])

3 Answers 3

4

If you want a circular iterator, use itertools.cycle. If you just want circular behaviour when indexing, you can use modulo-based indexing.

In [20]: a = [1, 2, 3, 4, 5]

In [21]: pos = 9

In [22]: a[pos % len(a)]
Out[22]: 5
Sign up to request clarification or add additional context in comments.

Comments

0

That is because when pos > 4 and pos < 10 your code throws an IndexError exception, and it then runs a[pos - len(a)] which will give the desired result.

However, when pos >= 10, the control will go to the Except block, but then the statement a[pos - len(a)] will also give an IndexError exception, becuase pos - len(a) would be greater than 4, since len(a) is a constant.

I would recommend you to implement a circular iterator about which coldspeed said in his answer, or do something like this if you want to follow your approach:

except IndexError:
    print(a[pos % len(a)])

P.S. You also don't need to put this whole thing in a try-except block. ^.^

2 Comments

Nit: Using modulo based indexing does not make your list a circular iterator, it only lets you index your list in a circular fashion. Also, you don't have to put your indexing code inside a try/except.
Oops. I was talking about the itertools.cycle. Gotta brush up me English 'mate. I just wrote how OP could implement this in his "algorithm", the try-except approach.
0

You want to print a[pos % len(a)], not a[pos - len(a)], as anything greater than 10, minus 5, is greater than 5.

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.