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
#4
I don't know that i would use range on the list.
All though there are other ways but, maybe like this

mylist = [5,[5, 3, 3],5,5,5] # List of numbers

def sum_nested_list(mylist):
    # set the finction variable
    total = 0
    # Loop through the list checking for other list
    for num in mylist:
        if type(num) == list: # If a list is found, get the sum and add to total
            total += sum(num)
        else:
            total += num # else add the num to total
    return total # return the total

print(sum_nested_list(mylist))
Output:
31
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Messages In This Thread
RE: Python Program to Find the Total Sum of a Nested List - by menator01 - Jan-23-2022, 06:28 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