python for loop and remove method

后端 未结 1 766
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 03:15

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.re         


        
相关标签:
1条回答
  • 2021-01-14 03:55

    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.

    0 讨论(0)
提交回复
热议问题