简体   繁体   中英

modify an array does not affect its length in outer loop

I have such a following example:

In [2]: l = list(range(10))                                                                                                   

In [3]: l                                                                                                                     
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [4]: for i in range(len(l)): 
   ...:     l.append(1) 
   ...:     print("yes") 
   ...:                                                                                                                       
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes

In this case, l append 'l' every time during the loop, so len(l) will increase by 1 every time.
I assumed this should be a infinite loop.

The result prove my prediction wrong,

How could understand this situation intuitively.

l is an mutable array, it's length is changing instantly during the loop?

len(l) is evaluated before the loop is entered.

On the other hand, for i in l will cause an infinite loop.

The len(l) statement is only evaluated when entering the loop. So really the code is executing for i in range(10).

The problem is that len() is evaluated once. However, to achieve something as you say you may use a while loop:

xs = [1]
i = 0

while i < len(xs):
  xs.append(1)
  i += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM