first non-null element in a list, otherwise None

Gerard Flanagan grflanagan at gmail.com
Thu Sep 2 11:28:39 EDT 2010


wheres pythonmonks wrote:
> This should be trivial:
> 
> 
> I am looking to extract the first non-None element in a list, and
> "None" otherwise.  Here's one implementation:
> 
>>>> x = reduce(lambda x,y: x or y, [None,None,1,None,2,None], None)
>>>> print x
> 1
> 
> I thought maybe a generator expression would be better, to prevent
> iterating over the whole list:
> 
>>>> x = ( x for x in [None,1,2] if x is not None ).next()
>>>> print x
> 1
> 
> However, the generator expression throws if the list is entirely None.
> 
> With list comprehensions, a solution is:
> 
>>>> x = ([ x for x in [None,1,2] if x is not None ] + [ None ] )[0]
> 
> But this can be expensive memory wise.  Is there a way to concatenate
> generator expressions?
> 
> More importantly,
> 
> Is there a better way?  (In one line?)
> 
> Thanks,
> 
> W

itertools.dropwhile(lambda x: x is None, inlist + [0]).next() or None





More information about the Python-list mailing list