Pran Pran - 7 months ago 27
Python Question

Getting the first non None value from list

Given a list, is there a way to get the first non-None value? And, if so, what would be the pythonic way to do so?

For example, I have:


  • a = objA.addreses.country.code

  • b = objB.country.code

  • c = None

  • d = 'CA'



In this case, if a is None, then I would like to get b. If a and b are both None, the I would like to get d.

Currently I am doing something along the lines of
(((a or b) or c) or d)
, is there another way?

Answer Source

You can use next():

>>> a = [None, None, None, 1, 2, 3, 4, 5]
>>> next(item for item in a if item is not None)
1

If the list contains only Nones, it will throw StopIteration exception. If you want to have a default value in this case, do this:

>>> a = [None, None, None]
>>> next((item for item in a if item is not None), 'All are Nones')
All are Nones