Recursive list sum

18-minute lesson · module-recursion-02

You are previewing this course as a guest

Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.

Sign in

Recursive list sum

18-minute lesson · module-recursion-02

  • Sum a flat list recursively without a loop.
  • Detect a sublist with `isinstance(item, list)`.
  • Recurse into nested lists to sum numbers at any depth.
  • Recognize the empty list as the natural base case.

Source attribution

Status: adapted

How to Think Like a Computer Scientist: Interactive Edition source · Recursion / Calculating the Sum of a List of Numbers

Adaptation notes. Reading rewritten in our voice. We extend the chapter's flat-list sum to arbitrarily nested lists, which is the natural "recursion shines here" payoff. Hidden tests cover flat lists, deeply nested lists, and empties.

License notes. Original chapter is GNU FDL 1.3 (Brad Miller, David Ranum, and the upstream Elkner/Downey/Meyers text). No verbatim text reproduced.