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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With