user3161743
user3161743

Reputation: 171

Python: Adding numbers in a list

The question is to iterate through the list and calculate and return the sum of any numeric values in the list.

That's all I've written so far...

def main():
    my_list = input("Enter a list: ")
    total(my_list)

def total(my_list1):
    list_sum = 0 
    try:
        for number in my_list1:
            list_sum += number
    except ValueError:
         #don't know what to do here

    print list_sum

main()

Upvotes: 0

Views: 416

Answers (4)

grandocu
grandocu

Reputation: 326

Using the generator removes the need for the below line but as a side note, when you do something like this for this:

try:
    for number in my_list1:
        list_sum += number
except ValueError:
     #don't know what to do here

You need to call float() on the number to force a ValueError when a string is evaluated. Also, something needs to follow your except which could simply be pass or a print statement. This way of doing it will only escape the current loop and not continue counting. As mentioned previously, using generators is the way to go if you just want to ignore the strings.

def main():
    my_list = input("Enter a list: ")
    total(my_list)
    return

def total(my_list1):
    list_sum = 0 
    try:
        for number in my_list1:
            list_sum += float(number)
    except ValueError:
        print "Error"
    return list_sum

if __name__ == "__main__":
    main()

Upvotes: 0

Ffisegydd
Ffisegydd

Reputation: 53718

You can use a generator expression such that:

from numbers import Number

a = [1,2,3,'sss']

sum(x for x in a if isinstance(x,Number)) # 6

This will iterate over the list and check whether each element is int/float using isinstance()

Upvotes: 3

PyWebDesign
PyWebDesign

Reputation: 197

Maybe try and catch numerical

this seams to work:

data = [1,2,3,4,5, "hfhf", 6, 4]
result= []
for d in data:   
    try:
        if float(d):
            result.append(d)
    except:
        pass    

print sum(result) #25, it is equal to 1+2+3+4+5+6+4

Upvotes: 1

Ben
Ben

Reputation: 52913

If you check to see whether the list item is an int, you can use a generator:

>>> a = [1, 2, 3, 'a']
>>> sum(x for x in a if isinstance(x, int))
6

Upvotes: 3

Related Questions