We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Dangers of Recursion

Recursion is great because it's simple and elegant (simple != easy). It's often the most straightforward way to solve a problem. But there are some dangers to be aware of:

  1. Stack overflow: Each function call requires a bit of memory. So if you recurse too deeply, you can run out of "stack" memory, which will crash your program. (This is what the famous website is named after.)
  2. If you don't have a base case, or your recursive calls never reach it, the function can keep calling itself until Python raises a RecursionError for exceeding the maximum recursion depth.
  3. Especially in a language like Python, recursion is often slower than a for loop because each function call adds overhead. Tail call optimization can help with this, but Python doesn't support it.