Editor

Python Program to Find the Sum of a Nested List

Intermediate · Lists

A nested list has lists inside it, sometimes several levels deep, like [1, [2, 3], [4, [5, 6]]]. This program adds up every number in it with a recursive function, which calls itself for each inner list it finds.

Program

sum_of_nested_list.py
def nested_sum(items):
total = 0
for item in items:
if isinstance(item, list):
total += nested_sum(item) # add up the inner list first
else:
total += item
return total
data = [1, [2, 3], [4, [5, 6]], 7, [[8], 9]]
print("Nested list:", data)
print("Sum of all numbers:", nested_sum(data))
Output
Nested list: [1, [2, 3], [4, [5, 6]], 7, [[8], 9]]
Sum of all numbers: 45

How it works

  1. isinstance(item, list) tells a number apart from an inner list.
  2. A number is added straight to total.
  3. An inner list is passed to nested_sum() again, and the sum it returns is added to total.
  4. Each call handles one level, so lists inside lists inside lists are added up correctly: 1 + 2 + ... + 9 = 45.

Other ways to write it

A list of lists, one level deep

A list of lists, one level deep
marks = [[78, 85, 90], [66, 72, 80], [91, 88, 95]]
total = 0
for row in marks:
print("Row", row, "sum:", sum(row))
total += sum(row)
print("Total of all rows:", total)
Output
Row [78, 85, 90] sum: 253
Row [66, 72, 80] sum: 218
Row [91, 88, 95] sum: 274
Total of all rows: 745

When every inner list sits at the same level, like rows of marks, a loop with sum() on each row is enough.

Without recursion, using a stack

Without recursion, using a stack
data = [1, [2, 3], [4, [5, 6]], 7, [[8], 9]]
total = 0
stack = [data] # lists still waiting to be added up
while stack:
current = stack.pop()
for item in current:
if isinstance(item, list):
stack.append(item) # deal with it later
else:
total += item
print("Sum of all numbers:", total)
Output
Sum of all numbers: 45

Inner lists are put on a stack to be handled later, so the program never calls itself and has no recursion limit.

Try it yourself

Change the function to count how many numbers the nested list holds instead of adding them.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises