Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first non None value from list

Tags:

python

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?

like image 248
Pran Avatar asked Aug 30 '13 13:08

Pran


People also ask

How do I remove none values from a list?

The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.

How do I remove all none values from a list in Python?

The Python filter() function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values.

How do I find none values in Python?

To check none value in Python, use the is operator. The “is” is a built-in Python operator that checks whether both the operands refer to the same object or not.

What happens if you append none to a list Python?

The Python append() method returns a None value. This is because appending an item to a list updates an existing list. It does not create a new one. If you try to assign the result of the append() method to a variable, you encounter a “TypeError: 'NoneType' object has no attribute 'append'” error.


1 Answers

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 
like image 171
alecxe Avatar answered Oct 08 '22 00:10

alecxe