[Tutor] "if clause" in list comprehensions.

Christian Witts cwitts at compuscan.co.za
Wed Oct 21 10:21:40 CEST 2009


Albert-Jan Roskam wrote:
> Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x? Or did I miss something?
>
> Cheers!!
> Albert-Jan
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Before you criticize someone, walk a mile in their shoes, that way 
> when you do criticize them, you're a mile away and you have their shoes! 
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
>
> --- On Tue, 10/20/09, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>   
>> From: Alan Gauld <alan.gauld at btinternet.com>
>> Subject: Re: [Tutor] "if clause" in list comprehensions.
>> To: tutor at python.org
>> Date: Tuesday, October 20, 2009, 12:29 AM
>> Ooops, hit send by mistake...
>>
>> "vince spicer" <vinces1979 at gmail.com>
>> wrote
>>
>>     
>>>> Lambda can save the day to keep everything on one
>>>>         
>> line, and leave variable
>>     
>>>> type the same:
>>>>
>>>> mylist = ['John', 'Canada', 25, 32, 'right']
>>>> new_list = [(lambda y: y.upper() if hasattr(y,
>>>>         
>> 'upper') else y)(a) for a in
>>     
>>>> mylist ]
>>>>
>>>>         
>>>>>>   ['JACK', 'CANADA', 25, 32,
>>>>>>             
>> 'RIGHT']
>>
>> In what way does lambda help?
>>
>> new_list = [y.upper() if hasattr(y, 'upper') else y for y
>> in mylist]
>>
>> does exactly the same and is shorter.
>>
>> lambda helps if you want to pass a function object around
>> but
>> defining it and immediately calling it means it can be
>> replaced
>> directly by the expression within the lambda.
>>
>> But using hasattr() still has the problem of failing if
>> upper is not a
>> callable attribute (or does something radical like
>> exiting)
>>
>>
>> -- Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/ 
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>     
>
>
>       
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>   
Python 2.5+ if memory serves me correctly.  I know 2.4 running on one of 
our servers does not support the else section.

-- 
Kind Regards,
Christian Witts




More information about the Tutor mailing list