[Tutor] List comprehension possible with condition statements?

Dave Angel davea at ieee.org
Wed Mar 3 10:03:28 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
>
>   

Are there any constraints on x and y ?  If you want to throw out all 
None values, then it's a ready problem.  You try it, and if it doesn't 
quite work, post the code. We'll try to help.

But if only the third value is special, then there's little point in 
making a comprehension of one value.  Just conditionally append the z 
value to the list containing x and y.

DaveA



More information about the Tutor mailing list