1
a = [[1,2,3],[4,1],[2,2,6],[3]]

the sum of a would print 24

I know for a single list such as [1,2,3] i can just do sum(a) but I'm struggling with a nested list.

Thank you.

2 Answers 2

6

This does not create a new temporary list:

sum(sum(b) for b in a)
Sign up to request clarification or add additional context in comments.

3 Comments

+1. This just as clear as sum(itertools.chain(*a)). However, I'm not sure why someone would simply rule out itertools.
Thanks for this, but i'm very new could you possibly explain what b is standing for? I just cannot wrap my head around it, maybe i need some sleep.
@jack: b is one of your sublists. To see how this works use a for-loop: for b in a:print b.
3
sum(sum(a, []))

The inner sum combines all the individual lists into one list. The outer sum then finds the actual sum.

For lists that are nested more than one deep, you can use this:

def recursiveSum(data):
    try:
        total = 0
        for item in data:
            total += recursiveSum(item)
        return total
    except TypeError: #data isn't iterable, it's probably a number
        return data

print recursiveSum([[[[1,2,3],[4,1]],[2,2,6]],3])

output:

24

1 Comment

This has the potential to horribly inefficient. Each time a list is added a new and ever larger list is created.

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.