Reputation: 282
Let l
be a list. In this python script, is the function len(l)
executed every time in the for loop?
for i in range(len(l)):
#do something here
If so, it would be very wasteful when len(l)
is large. We should introduce a=len(l)
and then use range(a)
in the for
loop so that len
function is only used once.
What about the following case?
for i in range(3+4):
#do something here
Is 3+4
computed every time or just once?
What about the for loop in C such as the following?
for (i = 1; i < 3+4; i++) {
do something here;
}
Upvotes: 1
Views: 87
Reputation: 144715
In Python, the for argument range(len(l))
is evaluated once and produces a range
object that acts like a generator when it is requested for each iteration of the loop until it reaches the end of the sequence. Thus len(l)
is only evaluated once. Note that depending on what you do in the loop body, a simpler for i in l:
might be more appropriate.
In the C expression for (i = 1; i < 3+4; i++)
, the test clause i < 3+4
is evaluated before each iteration of the loop and since 3+4
is a constant expression, the compiler evaluates it at compile time and just generates code to compare i
with 7
before the iteration of the loop.
Note however that if the loop is small, the compiler might expand it into a sequence of operations and remove the tests and increment completely.
Upvotes: 3