DormoTheNord DormoTheNord - 3 months ago 22
Python Question

Is it alright to call len() in a loop's conditional statement?

In C, it is considered bad practice to call strlen like this:

for ( i = 0; strlen ( str ) != foo; i++ )
// stuff

The reason, of course, is that it is inefficient since it "counts" the characters in a string multiple times.

However, in Python, I see code like this quite often:

for i in range ( 0, len ( list ) ):
# stuff

Is this bad practice? Should I store the result of len() in a variable and use that?


In Python, a for loop iterates through a list-like object, it doesn't have a conditional statement that is checked each time. To illustrate, the following two loops are functionally equivalent; the while loop is a direct translation of for (i=0; i< n; i++) { ... }, while the for loop is the Pythonic way of doing it:

i = 0
while i < n:
   # do some actions using i
   i += 1

for i in range(n):
   # do some actions using i

In the for loop, range(n) is evaluated before the loop starts, and then its return value is used in the loop. In other words, range(n) is evaluated once (and only once) to get the list* of values that i should take.

So in the specific example given, Python sees for i in range(0, len(list)), evaluates range(0, len(list)) (so len() is called once) and stores the output (it doesn't call range() (or len()) again).

(* in Python 3.x range() doesn't actually return a list, but when using it in a for loop there is no difference in functionality)