Python method for loop and delete

Suppose 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]

finally x is not clear. What for? and

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

this code is similar to code1. compare the two codes by code3, why they do not act like this:

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

I have another question about the / while loop when python starts:

for i in x 

or

while x

Is all the contents of x in memory / RAM? if so, what can I do if x is too large for better performance?

edit:

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

+4
source share
1 answer

When you speak for i in x, you use an iterator.

x . , (x), , .

for i in x : , , ( ) , , . while : .

, x:

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

x:

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

, x , - . - for i in x, , .

+3

Source: https://habr.com/ru/post/1599704/


All Articles