Row wise sum of nested list Python

This is a Python Program to find the total sum of a nested list using recursion.

Problem Description

The program takes a nested list and finds the total sum of the nested list using recursion.

Problem Solution

1. Initialize a variable to a nested list.
2. Pass the list as an argument to a recursive function to find the sum of elements of the list.
3. In the function, use a for loop and recursion to obtain the elements inside the sublists and store the summed up elements in a variable.
4. Return the total sum of the elements.
5. Print the sum of the nested list.
6. Exit.

advertisement
Program/Source Code

Here is source code of the Python Program to find the sum of a nested list using recursion. The program output is also shown below.

def sum1[lst]: total = 0 for element in lst: if [type[element] == type[[]]]: total = total + sum1[element] else: total = total + element return total print[ "Sum is:",sum1[[[1,2],[3,4]]]]
Program Explanation

1. A variable is initialized to a nested list.
2. The list is passed as an argument to a recursive function to find the sum of elements of the list.
3. In the function, A for loop and repeated recursion to obtain the elements inside the sublists.
4. The total sum of the elements is found out and is returned.
5. The sum of the elements in the nested list is printed.

Subscribe Now: Python Programs Newsletter | Important Subjects Newsletters
advertisement
advertisement
Runtime Test Cases
Case 1: Sum is: 10

Sanfoundry Global Education & Learning Series Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Become Top Ranker in Python Programming Now!
advertisement
« Prev - Python Program to Check Whether a String is a Palindrome or not Using Recursion
» Next - Python Program to find the factorial of a number without recursion
Next Steps:

  • Get Free Certificate of Merit in Python Programming
  • Participate in Python Programming Certification Contest
  • Become a Top Ranker in Python Programming
  • Take Python Programming Tests
  • Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:

  • Apply for Programming Internship
  • Apply for Python Internship
  • Buy Python Books
  • Buy Information Technology Books
  • Practice Programming MCQs

Video liên quan

Chủ Đề