0

I'm supposed to remove all odd numbers larger than 5, and then divide all even numbers with two. This should happen as a iterative process, i.e. a loop of some sort.

A = [12, 8, 9, 2, 18, 3, 15, 19, 6, 12, 15, 3, 20, 3, 13, 6, 1, 20, 13, 14]

for i in A:
    if i%2 == 1 and i>5:
        A.remove(i)
    else: pass
print(A)

for i in A:
    if i%2 == 0:
        A[A.index(i)] /= 2
    
    else: pass
print(A)   

In the first for-loop, 19 wont get removed, and I don't know why. If I exchange one of the other odds, 15 for example, with 19, then it gets removed. In the second for-loop, when I divide 12, the first one, with 2, it becomes 3. If I write 10 as the first number instead, it becomes 5. The 12 later in the list becomes 6 either way.

Why is this happening, and what can I do to make it work?

  • `A[A.index(i)]` won't work if there are duplicates, because `index(i)` is the index of the first occurrence, not the current one. Iterate over the array indexes, not the elements, or use `enumerate()` to iterate over both together. – Barmar Jan 22 '21 at 15:34
  • Don't modify a container while iterating it, append elements to another one instead. Also, *index* might not return what you think it does (when having duplicates). You can do both operations in a single loop. – CristiFati Jan 22 '21 at 15:34
  • Not related, but `A[A.index(i)]` is very inefficient. If you want the index of something, use `enumerate` (or just keep the index by hand) – juanpa.arrivillaga Jan 22 '21 at 15:41

0 Answers0