0

I made a list of indices of an array by

indexlist = [(x, y) for x, y in np.ndindex(a.shape)]

a is a 4x7 array. I was trying to figure out a way to get a list of every index in a particular column, except for one particular index in that column (In this example, index of interest is (1,2). I used this:

for i in indexlist:
if i[1] != pivot[1]:
    indexlist.remove(i)
    print(i)

(pivot = (1,2)). I expected this to give me a list with only (0,2)(1,2)(2,2)(3,2), but I get a much larger list. When I run it again, it removes a few more values. It gets to what I was expecting, but only after I run it 3 times. Why?

for i in indexlist:
if i[1] != pivot[1]:
    indexlist.remove(i)
    print(i)

(0, 0)
(0, 3)
(0, 5)
(1, 0)
(1, 3)
(1, 5)
(2, 0)
(2, 3)
(2, 5)
(3, 0)
(3, 3)
(3, 5)

for i in indexlist:
    if i[1] != pivot[1]:
        indexlist.remove(i)
        print(i)

(0, 1)
(0, 4)
(1, 1)
(1, 4)
(2, 1)
(2, 4)
(3, 1)
(3, 4)

for i in indexlist:
    if i[1] != pivot[1]:
        indexlist.remove(i)
        print(i)

(0, 6)
(1, 6)
(2, 6)
(3, 6)

for i in indexlist:
    if i[1] != pivot[1]:
        indexlist.remove(i)
        print(i)


print(indexlist)
[(0, 2), (1, 2), (2, 2), (3, 2)]

Clarification, I want to remove items from the list, but I do not understanmd why it doesn't remove the items (x,i) where i != 2 all at once.

Emily
  • 163
  • 1
  • 1
  • 9
  • 2
    You are deleting from your list as you iterate over it. Don't do that. – juanpa.arrivillaga Jul 11 '17 at 23:00
  • No, I want to delete from the list. I want to remove every element that isn't equal to (x,2) where x is any value from 1 to 4. – Emily Jul 11 '17 at 23:03
  • What I was doing was an inefficient way to solve a problem and halfway through, I figured out a better way. However, it doesn't solve the problem of why this has to run 3 times to do what I want it to. – Emily Jul 11 '17 at 23:04
  • 2
    @Emily The essence of the problem is the same. When you delete an element, your loop counter skips one element, because the list shrunk by one element. Just append the items you want to keep in a new list, or use a list comprehension. – cs95 Jul 11 '17 at 23:07
  • I'm not sure how that response contradicts what I was saying... you are deleting from the list as you iterate over it. That causes your iterator to skip elements. This is why you require multiple passes. Check out the answer in the duplicate, it explains what is going on. – juanpa.arrivillaga Jul 11 '17 at 23:12

0 Answers0