1

I try to capture multiple IndexErrors in the same loop, yet I can only capture the first one. This question might be related to my question, yet I cannot understand it. If it helps, I am using Enthought Canopy 1.6.2 on Windows 10 and Python 2.7.13.

import numpy as np

some_array=np.zeros(10)
some_set=[2,4,15,19]
for sense in some_set:
    try:
        some_array[sense]=1
    except IndexError:
        some_set.remove(sense)
        print some_set, "sense"

The output I receive is:

[2, 4, 19] sense

While I want an output of the form

[2, 4, 19] sense

[2, 4] sense

Community
  • 1
  • 1
ck1987pd
  • 267
  • 2
  • 11

2 Answers2

2

Your issue comes forth from the fact that you are modifying the array you are looping through. In python a for x in y: is basically the same as for i in range(len(y)): x = y[i].

The issue is that you are at index 2 in your loop, which yields the element 15. You then catch the error and remove 15 from the array. All good. However, now the array you are looping through is [2, 4, 19] and you just ended an iteration, letting Python know to see what the element is at index 3. There is no index 3 anymore, so Python will terminate the loop.

To stop your problem from occurring, simply loop over a copy of the array, so that you are not altering the array you are also checking, using .copy() or [:].

import numpy as np
some_array=np.zeros(10)
some_set=[2,4,15,19]
for sense in some_set[:]:  # This line was changed to use [:]
    try:
        some_array[sense]=1
    except IndexError:
        some_set.remove(sense)
        print some_set, "sense"
Vulcano
  • 155
  • 9
1

The whole loop doesn't stop.

Try to add a number like 21 to the end of your set, and I think you'll see what's happening.

Python is reading index 0 of the loop, then 1, then 2, etc. So it reads 2 (index 0,) then 4 (index 1,) then 15 (index 2) and it deletes it. But then the list is [2, 4, 19, 21] and it reads index 3.

[2, 4, 19, 21] sense
[2, 4, 19] sense

As bereal mentions, you should avoid modifying a set when iterating over it.

ck1987pd
  • 267
  • 2
  • 11
aschultz
  • 1,658
  • 3
  • 20
  • 30