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
forloop 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; thewhileloop is a direct translation offor (i=0; i< n; i++) { ... }, while theforloop is the Pythonic way of doing it:In the
forloop,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 thatishould take.So in the specific example given, Python sees
for i in range(0, len(list)), evaluatesrange(0, len(list))(solenis called once) and stores the output (it doesn’t callrange(orlen) again).(* in Python 3.x
rangedoesn’t actually return a list, but when using it in a for loop there is no difference in functionality)