[Tutor] List comprehension possible with condition statements?

C.T. Matsumoto tmatsumoto at gmx.net
Wed Mar 3 09:50:59 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
>   
Yes a list comprehension can have if statements.

You can get the values of x and y pretty simply:

 >>> [i for i in mylist if i]
[3, 4]


T


More information about the Tutor mailing list