Does range() not evaluate its argument every time?

前端 未结 3 840
我寻月下人不归
我寻月下人不归 2021-01-15 11:22

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

相关标签:
3条回答
  • 2021-01-15 12:05

    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.

    0 讨论(0)
  • 2021-01-15 12:05

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

    0 讨论(0)
  • 2021-01-15 12:06

    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.

    0 讨论(0)
提交回复
热议问题