Convert empty string to zero

I am doing something like this to sum all values ​​from start to finish.

big_list = line.split(delim)
sum( [int(float(item)) for item in big_list[start:end]] )

      

Sometimes the element big_list

may be empty, in which case the conversion fails. Can I make it work with empty lines in an elegant way without changing too much?

+3


source to share


1 answer


Assuming empty elements should be zero:

sum(int(float(item)) for item in big_list[start:end] if item)
                                                   # ^ skip over ""

      



Note that:

  • sum

    can take a generator expression as an argument, no need to create a list; and
  • An empty string ""

    evaluates to False

    -y, so this is equivalent if item != ""

    .
+6


source







All Articles