Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

python - Does range() not evaluate its argument every time?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...