[Tutor] list comprehension, testing for multiple conditions

eryksun eryksun at gmail.com
Fri Aug 24 04:34:31 CEST 2012


On Thu, Aug 23, 2012 at 9:39 PM, Dave Angel <d at davea.name> wrote:
>
>>     theGoodLines = [line.strip("\n") for line in lines if "v " ==
>> line[0:2]]
>
> Better to use startswith(), since short lines will cause the if
> expression above to blow up.

A slice won't blow up. At worst you get an empty string. But the slice
does create a temporary string, and subsequently the expression uses a
high-level compare.

startswith is more efficient and flexible in CPython. It does a
low-level memory compare (memcmp). You can pass it a single string or
a tuple of strings to match against, and you can set a start/stop
position.


More information about the Tutor mailing list