[Tutor] List comprehension possible with condition statements?

Christian Witts cwitts at compuscan.co.za
Wed Mar 3 10:02:14 CET 2010


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




More information about the Tutor mailing list