[Tutor] list comprehension, testing for multiple conditions

Dave Angel d at davea.name
Fri Aug 24 06:20:36 CEST 2012


On 08/23/2012 10:34 PM, eryksun wrote:
> 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. 

You're right of course.  For some reason I was looking at it as though
it were simple subscripting, which can blow up (once the newline has
been discarded, there might not be a [0] item.

> 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.
> 
> 


-- 

DaveA


More information about the Tutor mailing list