Reputation: 47
If I have a list of strings stored in a variable called b_split[1]. Basically the 1st position in b_split contains these latitude values as a string.
['10.2']
['10.4']
['10.5']
I want to be able to sum them up..
for i in text_file:
latitude = float(b_split[1])
print sum(latitude)
It gives me an error that the 'float' object is not iterable
Upvotes: 2
Views: 11349
Reputation: 37279
If you don't need the resulting list and simply want to sum the items, you could try passing the items you care about directly to the sum
function:
In [1]: my_list = ['10.2', '10.4', '10.5']
In [2]: sum(float(item) for item in my_list)
Out[2]: 31.1
This creates a generator of the float
of each item in your list, and sums each item. As alluded to by @avasal, the reason you are getting your error is because you are actually reassigning latitude
on each iteration, and your final result is a float (and not a list/iterable):
In [3]: for item in my_list:
...: my_var = float(item)
...:
In [4]: print my_var
10.5
Therefore when you try to sum
it, you get the error you see above because sum sums the elements of an iterable. Since you can't iterate over a float
, you get the not iterable
error.
Upvotes: 0
Reputation: 14864
latitude should be a list
and it should be
latitude.append(float(b_split[1]))
and finally
print sum(latitude)
Upvotes: 2