A common reason people hit recursion limits when flattening nested lists is because the recursive approach doesn’t scale well with deeply nested structures. In practice, an iterative solution is usually safer and easier to reason about.
One simple pattern is to use an explicit stack instead of recursion. You start with the original list on the stack, then keep popping elements. If the element is a list, you push its contents back onto the stack; if it’s not, you add it to the result. This mimics recursion but avoids call-stack limits entirely.
The key detail is preserving order. To do that, you typically push items onto the stack in reverse order so they come out correctly when popped.
This approach is:
If you only need shallow flattening, tools like itertools.chain can help, but for unknown or arbitrary nesting depth, an explicit stack is usually the most robust solution.
In production code, I’ve found this pattern clearer than recursive helpers once the nesting gets non-trivial.