Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 800
DormoTheNord Avatar asked Mar 31 '12 05:03

DormoTheNord


People also ask

Is for loop conditional?

The While loop and the For loop are the two most common types of conditional loops in most programming languages.

What are the conditional statements in Python?

Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions. The conditions are evaluated and processed as true or false. If this is found to be true, the program is run as needed.

How do you break out of an IF statement in Python?

Exit an if Statement With the Function Method in Python We can use an alternative method to exit out of an if or a nested if statement. We enclose our nested if statement inside a function and use the return statement wherever we want to exit.

What does while Len mean in Python?

while len(list1) and len(list2): This: while list1 and list2: They are both semantically the same - they mean while both lists have contents to continue looping. Both zero and an empty list test False in a boolean context, and when a list is empty, it's length is zero.


3 Answers

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)

like image 197
huon Avatar answered Oct 12 '22 13:10

huon


Writing for i in range(len(whatever)) is poor style in Python. As others have mentioned, direct iteration is available via for element in whatever. However, people keep doing it anyway for two reasons:

  1. They're C programmers and haven't wrapped their heads around direct iteration.

  2. They want to modify the list while iterating through it, or otherwise need the indices. If this is the case, the Pythonic way to do it is the enumerate function: for i, element in enumerate(whatever).

like image 43
Taymon Avatar answered Oct 12 '22 13:10

Taymon


This is fine in python because the range function creates a list that the for loop subsequently uses. Therefore len is only called once. Also, you don't need the extra 0 there because range starts counting from 0 if no extra options are there.

As a side note, you'll usually want to use xrange instead since it creates a generator that is evaluated lazily.

like image 40
Squazic Avatar answered Oct 12 '22 13:10

Squazic