Python Forum
Python Program to Find the Total Sum of a Nested List
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Program to Find the Total Sum of a Nested List
#6
Haha @menator01 , you are cheating! Smile It would work fine if the list would remain limited to two dimensions, but it it is't. Vlearner had a list with a deeper nesting level: [[4,5],[7,8,[20]],100]. When you run your code on this list you get:
Error:
Traceback (most recent call last): File "/home/ibreeden/PycharmProjects/Forum/forum02.py", line 43, in <module> print(sum_nested_list(mylist)) File "/home/ibreeden/PycharmProjects/Forum/forum02.py", line 33, in sum_nested_list total = total + sum(num) TypeError: unsupported operand type(s) for +: 'int' and 'list'
@vlearner : your code is almost correct, you must change line 13 to
total += sum_nested_list(l[j])
... or else you lose the result of your recursive call.

(Jan-23-2022, 04:53 PM)vlearner Wrote: I checked this solution but I am not getting how the code works. can anyone explain the logic of code?
The algorithm is straigtforward. If you would pass a list with integers to your function, it would return the sum of the numbers. But if one of the elements of the list is again a (nested) list, then this list is handled by the (recursive) call to the same function. In that case the returned sum must be added to the total.
Reply


Messages In This Thread
RE: Python Program to Find the Total Sum of a Nested List - by ibreeden - Jan-23-2022, 06:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Program to find Mode of a list PythonBoy 6 1,341 Sep-12-2023, 09:31 AM
Last Post: PythonBoy
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,883 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  List all possibilities of a nested-list by flattened lists sparkt 1 1,061 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Find (each) element from a list in a file tester_V 3 1,396 Nov-15-2022, 08:40 PM
Last Post: tester_V
  read a text file, find all integers, append to list oldtrafford 12 4,182 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  find some word in text list file and a bit change to them RolanRoll 3 1,674 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  How to find the second lowest element in the list? Anonymous 3 2,282 May-31-2022, 01:58 PM
Last Post: Larz60+
  Updating nested dict list keys tbaror 2 1,392 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Find the highest value of a list Menthix 4 2,083 Oct-29-2021, 02:32 PM
Last Post: Menthix
  Looping through nested elements and updating the original list Alex_James 3 2,275 Aug-19-2021, 12:05 PM
Last Post: Alex_James

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020