[Tutor] list comprehension, testing for multiple conditions

Alan Gauld alan.gauld at btinternet.com
Wed Aug 22 18:16:54 CEST 2012


On 22/08/12 10:51, Pete O'Connell wrote:

>> theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListStripped if "vn" not in x  and "vt" not in x and x!= ""]
>
> It works but what I don't understand about this line is why the ands
> are not ors

Because 'or' would include x if any one of the conditions was true.

For example if 'vt' existed but not 'vn' then the line would be included 
because vn was not in the line, even though vt was.

We are all assuming that you want to exclude the line if any of the 
phrases is present.

Thats why I actually prefer the multiple if version that Peter posted:

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.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list