4
import math
lists =  [1,[2,3],4]
total = 0
for i in range(len(lists)):
    total += sum(i)
print(total)

I want it to print,

>>>10

But throws an error.

I would like it to get it to add all numbers, including the ones within the nested if.

Jack
  • 2,891
  • 11
  • 48
  • 65

3 Answers3

7

In your program, for i in range(len(lists)) - evaluates to 3 as the lists object has 3 element. and in the loop total += sum(i) it would try to do a int + list operation, which results in an error. Hence you need to check for the type and then add the individual elements.

def list_sum(L):
    total = 0  
    for i in L:
        if isinstance(i, list): 
            total += list_sum(i)
        else:
            total += i
    return total

This is @pavelanossov 's comment - does the same thing, in a more elegant way

sum(sum(i) if isinstance(i, list) else i for i in L)
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 1
    `sum(sum(i) if isinstance(i, list) else i for i in L)` – Pavel Anossov Apr 06 '13 at 21:23
  • This is telling me nested_sum is not defined, sorry for missing something, but what should nested sum be? Thanks. – Jack Apr 06 '13 at 21:24
  • sorry - typo . just fixed it. – karthikr Apr 06 '13 at 21:25
  • For me, `sum(sum(i) if isinstance(i, list) else i for i in L)` only works for lists nested at most two levels. This list fails: `L = ([[1, 1, 1], [1, [1, 1]], 1])`. Not as elegant, but @karthikr function list_sum(L) above works for lists of any level, because of recursion. – ColoradoGranite Nov 07 '17 at 16:31
6

You can use flatten function in the compiler.ast module to flatten the list. Then simply sum up all the elements.

>>> lists =  [1,[2,3],4]
>>> from compiler.ast import flatten
>>> sum(flatten(lists))
10

EDIT: Only works with Python 2.x

Faruk Sahin
  • 8,406
  • 5
  • 28
  • 34
0

numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array which is what we require in OP example

import numpy as np 

list1 =  [1,[2,3],4]
M = np.hstack(list1) 
print(np.sum(M))

gives

10

[Program finished]
Subham
  • 397
  • 1
  • 6
  • 14