Recap - Sum Nested List
Part of the Logic & Flow section of Coddy's Python journey — lesson 62 of 78.
Challenge
EasyWrite a recursive function named sum_nested that takes a nested list nested_list as an argument. The function should:
- Add all the integers in the list, including integers in any sublists.
- Return the total sum as an integer.
You can check if an element is a list using
isinstance(element, list)
Example Input:
nested_list = [1, [2, 3], [4, [5, 6]], 7]Example Output:
28Try it yourself
def sum_nested(nested_list):
total = 0
for element in nested_list:
if isinstance(element, list): # Check if the element is a list
# TODO: Recursively call sum_nested on the sublist and add to total
pass
else:
# TODO: Add the integer directly to total
pass
return totalAll lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter