LearnFrenzy
Sign in Take a free test

Recursion · Predict the Output · Question 12

Summing a nested list Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following Python program?

main.py
def deep(x):
    return sum(deep(i) for i in x) if isinstance(x, list) else x

print(deep([1, [2, [3, 4]], 5]), deep([]), deep(7))
  • A 8 0 7
  • B 15 None 7
  • C 15 0 7 Correct
  • D TypeError
Correct Answer: Option C

Lists are summed recursively; plain numbers are returned as they are. sum of an empty generator is 0.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links