-4
A=list(range(1,121))
for i in A:
    A.remove(i)
print(A)

Shouldn't it be empty? I really don't get this..

1 Answers1

2

You typically don't want to modify lists you're iterating over because you will get weird results like what you're running into.

You have a list of numbers, 1-121. You remove the first one, everything shifts down in memory so 2 is now in the zeroeth position. Do range 2-122 and you'll get only odd numbers.

 x = [1, 2, 3, 4, 5, 6]
 for i in x:
     x.remove(i)
     #first time through x = [2, 3, 4, 5, 6]
                           #  ^ i is still pointing here though and the next time
                           #    through it will be pointing at 3 (i = 2)
Billy Ferguson
  • 1,429
  • 11
  • 23