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

2
  • possible duplicate of Remove items from a list while iterating in Python Commented Jul 26, 2015 at 5: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. Commented Jul 26, 2015 at 9:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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] >>>
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) )
@derman ‛i‛ doesn't actually take those values, but the underlying iterator does. ‛i‛ is 1 and then 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.