-1

Pic

I was creating 'sieve of eratosthenes' in python and i found using 'remove' while operating 'for' loop removes only odd numbers (or even index element).

I thought it would remove all things in 'arr' list, removing its elements itself.

Can Anyone explain this?

Here is the Code

arr = list(range(1, 11))
for i in arr:
    arr.remove(i)
print(arr)

p.s. Sorry for bad gramma.

Dandlion
  • 1
  • 1
  • As a note to those who voted to close as dup, this case is a bit different from the usual cases, in that they really wanted to empty the ENTIRE list, not just a few elements. – Tim Roberts Jan 07 '22 at 06:00
  • @TimRoberts Does that matter? The question is the same. – Kelly Bundy Jan 07 '22 at 06:05
  • But a different answer is needed. – Tim Roberts Jan 07 '22 at 06:10
  • @TimRoberts I don't think so. Not really. Unless you imagine an additional question that's not actually there ("How can I achieve what I want?"). – Kelly Bundy Jan 07 '22 at 06:12
  • @TimRoberts I mean, even your own "answer" only "answers" with *"The internal pointers get all screwed up"* (the rest is fluff that doesn't address the question). You can say the exact same thing at the other questions (partly because it's so vague/vacuous). – Kelly Bundy Jan 07 '22 at 06:41

1 Answers1

0

You should not modify a list while you are iterating it. The internal pointers get all screwed up. In this case, to clear a list without just assigning a new object, you can do:

arr[:] = []
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • I suppose I should say "should not" when I post this advice, which happens about twice a week. – Tim Roberts Jan 07 '22 at 05:59
  • Thanks for your reply. I didn't know what happpens if I modify iterating list. By the way, can I use `arr = []` this code to clear the list? Is there anything different using slicer? – Dandlion Jan 07 '22 at 09:06
  • There is a big difference, but it only matters in some circumstances. Using the slice notation modifies the existing list object. Using the assignment creates a NEW list object and discards the old one. If, for example, `arr` was a parameter in a function, then using the assignment means you are now working with a different list object. Your changes will not be seen by the caller. Whether that's good or bad depends on your design. – Tim Roberts Jan 07 '22 at 19:30