pythonlistloopsfor-loopnumbers

Summing up elements in a list in python using a for loop


While working on a program that creates bars out of sets of numbers in a list, I found that adding up items in my list doesn't work. I thought the best way to do this is just to make a for loop.

Here's my list:

phonelist = [[12,14,16,17,18],[16,23,54,64,32]]

And then I try to add this up with a for loop

numphone = 0
for x in len(phonelist[0]):
    numphone = numphone + x

Yet I get this error:

TypeError: 'int' object is not iterable

What should I do?


Solution

  • >>> phonelist = [[12,14,16,17,18],[16,23,54,64,32]]
    >>> [sum(li) for li in phonelist]
    [77, 189]
    >>> sum([sum(li) for li in phonelist])
    266
    

    or:

    >>> sum(sum(li) for li in phonelist)    # generator expression...
    266
    

    If you are trying to create individual categories, you can use a dict:

    data={'Bar {}'.format(i):sum(li) for i, li in enumerate(phonelist, 1)}
    data['Total']=sum(data.values())
    
    print data
    {'Bar 2': 189, 'Bar 1': 77, 'Total': 266}
    

    Then if you want to produce a simple bar graph:

    for bar in sorted(data.keys()):
        print '{}: {}'.format(bar, int(round(25.0*data[bar]/data['Total']))*'*')
    

    Prints:

    Bar 1: *******
    Bar 2: ******************
    Total: *************************