0

I have some easy code:

a = [1,2,3,4,3,3,5]
for letter in a:
  print (letter)
  if letter == 3:
     a.remove(letter)

print ('a=',a)     

The output shows:

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

I expect to see:

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

What is happening? It seems in the loop that the "a" list is also being updated simultaneously. How can I fix the for loop to get the expected output?

Peter Brittain
  • 13,489
  • 3
  • 41
  • 57
TripleH
  • 447
  • 7
  • 16

1 Answers1

-1

It's removing the item at index 3, not the item with the value of 3. The following list comprehension does what you want.

a = [letter for letter in a if letter != 3]

[edit] Nope, I was wrong about "remove" - I confused it with "pop"

philngo
  • 913
  • 7
  • 12