[Tutor] list comprehension, testing for multiple conditions

ALAN GAULD alan.gauld at btinternet.com
Thu Aug 23 00:27:25 CEST 2012


Note uits not just that its on multiple lines, 

its the fact it has three distinct if statements. 
All of them must be satisfied to be included 

in the comprehension.

You could do it on 3 lines with one if statement:

theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListStripped
                                      if "vn" not in x and
                                         "vt" not in x and
                                          x!= ""]

But I still think the three if statements are clearer.
However, if you need to use 'or' instead of 'and' then you 

need to go back to a compound statement but multi-line 

layout still aids legibility.


Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/



>________________________________
> From: Pete O'Connell <pedrooconnell at gmail.com>
>To: Alan Gauld <alan.gauld at btinternet.com>; tutor at python.org 
>Sent: Wednesday, 22 August 2012, 22:27
>Subject: Re: [Tutor] list comprehension, testing for multiple conditions
> 
>On Thu, Aug 23, 2012 at 4:16 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>> theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListStripped
>>                                                 if "vn" not in x
>>                                                 if "vt" not in x
>>                                                 if x!= ""]
>>
>> It's slightly more verbose but it makes the rules more explicit, IMHO.
>
>I agree, it seems easier to read when written on multiple lines. I'll
>do it that way,
>Thanks
>Pete
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120822/a660d171/attachment-0001.html>


More information about the Tutor mailing list