0

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?

4 Answers 4

7
>>> 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: *************************
Sign up to request clarification or add additional context in comments.

Comments

2

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].

1 Comment

Of course @dawg's answer is a much more Pythonic method of doing what you're trying to do.
2
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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.