-1
A = [2,4,6,8,10,12]

for a in A:
    if a%2 == 0:  # If 2 divides a, remove a from A
    A.remove(a)

    print(A)

When I execute this block of code, the console output is [4,8,12].

My understanding of this code is that if any of the elements in [A] are divisible by 2, then we remove them from the list. In the list above, all elements are in fact divisible by 2, but only 2, 6, and 10 were removed. Anyone care to explain why 4, 8, and 12 were not removed?

Swifty
  • 839
  • 2
  • 15
  • 40

1 Answers1

0

Removing elements from a list while you're iterating through it messes up the iteration. You should use the filter function or a list comprehension instead.