Reputation: 2299
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?
Upvotes: 0
Views: 8258
Reputation: 103704
>>> 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: *************************
Upvotes: 7
Reputation: 88977
The best solution to this is to use the sum()
built-in function. One method, as given in other answers to this question, is to sum each sumlist, then sum those subtotals.
However, a better solution is to flatten the sublists - this is best achieved with itertools.chain.from_iterable()
.
sum(itertools.chain.from_iterable(phonelist))
This is an optimal solution as it means that you do not have to perform a lot of separate sum operations, or create an intermediate list. It will also work lazily if your data is a lazy source, making your code more memory-efficient and spreading the processing load.
Upvotes: 1
Reputation: 1482
numphone = 0
for x in phonelist[0]:
numphone = numphone + x
This should work. You iterate overt the list, not over the length of it, since the length is an integer and iterating over an integer doesn't make sense
Upvotes: 2
Reputation: 405675
len(phonelist[0])
is an int, so you can't loop over it. You can change that to
for x in phonelist[0]:
This way x
will take on each value of phonelist[0]
.
Upvotes: 2