[Tutor] List comprehension possible with condition statements?

Alan Gauld alan.gauld at btinternet.com
Wed Mar 3 09:46:39 CET 2010


"Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote

> 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]
> 

Assuming you actually mean that you don;t want to include 
any item that is None you can use an if clause at the end 
of the comprehension:

mylist = [irtem for item in aList where item != None]

and aList is any list, which could be [x,y,z] in your example.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list