PK-Paulina
PK-Paulina

Reputation: 21

How to sum certain floats in a list

I wonder how to sum up only the floats in this list,

list = ['abc', 3.0, 2.0, 2.0, 0.0, 1.0, 0.0, 0.0]

I can't find out how to exclude the first string. I would like to do something with

range(1, len(list))

as it will need to work on lists with longer lengths, maybe something similar to it with the same effect? For python 3

Upvotes: 2

Views: 116

Answers (2)

Sanjay Thapa
Sanjay Thapa

Reputation: 98

my_list = ['abc', 3.0, 2.0, 2.0, 0.0, 1.0, 0.0, 0.0]
sum = 0
for i in my_list:
    if type(i) is float:
        sum += i
print(sum)

This will result the sum to 8.0

Upvotes: 1

CDJB
CDJB

Reputation: 14546

You can use a generator in sum() and isinstance() to check if something is a float.

>>> lst = ['abc', 3.0, 2.0, 2.0, 0.0, 1.0, 0.0, 0.0]
>>> sum(x for x in lst if isinstance(x, float))
8.0

Note you should not use list as a variable name as it will overwrite the built in list class.

Upvotes: 2

Related Questions