Alice
Alice

Reputation: 1400

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?

Upvotes: 1

Views: 131

Answers (3)

Alberto Bonsanto
Alberto Bonsanto

Reputation: 18042

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

Upvotes: 0

foobarbaz
foobarbaz

Reputation: 508

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

Upvotes: 0

gmds
gmds

Reputation: 19885

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

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

Upvotes: 3

Related Questions