[Tutor] List comprehension possible with condition statements?

Jojo Mwebaze jojo.mwebaze at gmail.com
Wed Mar 3 10:20:52 CET 2010


Thanks to everyone, nice ideas!
cheers


On Wed, Mar 3, 2010 at 10:02 AM, Christian Witts <cwitts at compuscan.co.za>wrote:

> Jojo Mwebaze wrote:
>
>> Hi There,
>>
>> i would like to implement the following in lists
>>
>> assuming
>>
>> x = 3
>> y = 4
>> z = None
>>
>> i want to create a dynamic list such that
>>
>> mylist = [ x , y, z ] ,   if z in not None
>>
>> if z is None then
>>
>> mylist = [x,y]
>>
>> Anyhelp!
>>
>> cheers
>>
>> Jojo
>>
>>
>>
>>
>>
>> ------------------------------------------------------------------------
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> <output function> | <variable> for <input set>, <predicate>
>
> So something like `x**2 for x in [1, 2, 3, 4, 5, None, 9] if x != None`
> would iterate over your input set pumping the current item into the variable
> x, it will check "if x != None" and if that condition evaluates true it will
> perform the function you set out to perform.
>
> The predicate section acts as a filter to your data set ensuring the
> variable you are working with meets certain conditions.  If you wanted to
> for eg. still accept the None but perform a different function on it Python
> does allow it like `x**2 if x else 'Not a number' for x in [1, 2, 3, 4, 5,
> None, 9]`.
>
> Hope that helps.
>
> --
> Kind Regards,
> Christian Witts
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100303/d6d4ca20/attachment.html>


More information about the Tutor mailing list