pythonlistlist-comprehensionnonetypefloor

Round list values with list comprehension including None


I want to round down values of a list ignoring None.

Given a list without None values I would do it like:

import math        
value_list = [1.5, 2.3, 3.2, 4.7]
rounded_list = [math.floor(elem) for elem in value_list]

A list including None values gives an error:

import math        
value_list = [1.5, 2.3, None, 4.7]
rounded_list = [math.floor(elem) for elem in value_list]
TypeError: must be real number, not NoneType

I have this solution but I'm wondering, if there is a one-liner for it

import math 
value_list = [1.5, 2.3, None, 4.7]

for i in range(len(value_list)):
    try:
        value_list[i] = math.floor(value_list[i])
    except:
        pass    

Furthermore this solution is skipping the None values and I explicitly want to keep them.


Solution

  • Option 1. Rounded values including None

    rounded_list = [None if elem is None else math.floor(elem) for elem in value_list]
    

    Option 2. Rounded values without None

    rounded_list = [math.floor(elem) for elem in value_list if not elem is None]