Is it alright to call len() in a loop's conditional statement?
Posted
by
DormoTheNord
on Stack Overflow
See other posts from Stack Overflow
or by DormoTheNord
Published on 2012-03-31T05:01:15Z
Indexed on
2012/03/31
5:29 UTC
Read the original article
Hit count: 142
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?
© Stack Overflow or respective owner