4

assume we have a list , and I want to make it clear one by one. look at this code :

#code1
>>> x=[9,0,8,1,7,2,5]
>>> for i in x :
      x.remove(i)
>>> x
[0, 1, 2]

at last x are not clear . why ? and

#code2:
>>> for i in x :
      x.remove(x[0])
>>> x
[7, 2, 5]

this code is like code1. compare the two codes by code3, why they are not act like this one:

#code3:
>>> while x:
    x.remove(x[0])
>>> x
[]

I have another question about for/while loop , when python run :

for i in x 

or

while x

does all of x content are in memory/RAM ? if yes, what I can do when x are too big , for better performance?

edit:

plz explain about difference of outputs in codes: enter image description here

Community
  • 1
  • 1
Zero Days
  • 851
  • 1
  • 11
  • 22
  • possible duplicate of [Remove items from a list while iterating in Python](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) – wwii Jul 26 '15 at 05:22
  • @wwii Yes, Just the first part of the question. The second part is related to the performance of the for/while loop which is not covered in the question you linked. – Marcellinov Jul 26 '15 at 09:44

1 Answers1

3

When you say for i in x, you are using an iterator.

This iterator stores the current position in x as the loop runs. If you modify the status of the object over which you are iterating (x) while the loop is still going, the iterator object does not know this.

That's why using the for i in x doesn't run the correct number of times: the size of the list shrinks when you remove elements, leading to the iterator being beyond the end of the (now shrunken) list, causing the loop to terminate even though the list is not yet empty. The while loop isn't using an iterator: it's just a conditional check.

You can see this in action by iterating over a copy of x:

for i in x[:]:
    x.remove(x[0])

Or by iterating over the indices in x:

for i in range(len(x)):
    x.remove(x[0])

To answer your second question, if x is big, use a generator function instead of a real list. Iterating over the results of the generator still looks like for i in x, but the list does not need to be entirely materialized for you to iterate over it.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • can you explane about the difrence output in codes :>>> list=[1,2,3,4] >>> for i in list: list.remove(i) >>> list [2, 4] >>> >>> >>> list=[1,2,3,4] >>> for i in list: list.remove(list[0]) >>> list [3, 4] >>> – Zero Days Jul 26 '15 at 08:00
  • ```for i in list: list.remove(i) ``` explanation: first, i=0, so you remove list[0] (which is 0). then i = 1 and list = [2,3,4], so you remove list[1] which is 3. Then i = 2 and list = [2,4], so the iterations ceases ( i >= len(list) ) – dermen Jul 26 '15 at 09:18
  • @derman ‛i‛ doesn't actually take those values, but the underlying iterator does. ‛i‛ is 1 and then 3. – Borealid Jul 26 '15 at 17:59