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
Nested list: [1, [2, 3], [4, [5, 6]], 7, [[8], 9]] Sum of all numbers: 45
How it works
isinstance(item, list)tells a number apart from an inner list.- A number is added straight to
total. - An inner list is passed to
nested_sum()again, and the sum it returns is added tototal. - 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
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
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.
Related programs
- Flatten a Nested List
- Find the Sum of Elements in a List
- Find the Sum of a List Using Recursion
- Work with a Nested Dictionary
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises