Does range() not evaluate its argument every time?

2020-03-28 03:35发布

l is passed as an argument to range function whose value is modified inside for loop, but the loop is going for 10 times instead of 5.

i = 0
l = 10
for i in range(l):
    print i,l
    l = l-1

The output is

0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
9 1

While I expected

0 10
1 9
2 8
3 7
4 6

Does range() evaluates value for the first time only or something else is the reason?

3条回答
Evening l夕情丶
2楼-- · 2020-03-28 03:48

range(l) is evaluated once, what is being updated is the value of l in the print statement.

查看更多
Bombasti
3楼-- · 2020-03-28 04:00

The issue is not how often range evaluates its argument, but how often for item in sequence evaluates sequence. The answer is once. When you write for i in range(l), range(l) is evaluated once and that's it.

查看更多
Explosion°爆炸
4楼-- · 2020-03-28 04:03

No, the for loop evaluates the iterable expression just once.

range() is called once, and the for loop then iterates over the result.

Quoting from the for statement documentation:

The expression list is evaluated once; it should yield an iterable object.

emphasis mine.

查看更多
登录 后发表回答