How do you flatten a nested list in Python to bring all elements into the outermost list?
💡 Model Answer
To flatten a nested list in Python you can use a recursive helper that walks through each element. If the element is a list, recurse into it; otherwise, append it to a result list. This approach handles arbitrarily deep nesting. Example:
from typing import List, Any
def flatten(lst: List[Any]) -> List[Any]:
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return resultComplexity: The algorithm visits each element once, so time complexity is O(n) where n is the total number of elements across all nested levels. Space complexity is also O(n) for the output list, plus O(d) for recursion stack where d is the maximum depth. For very deep nesting you could replace recursion with an explicit stack to avoid recursion limits. This method is commonly used in interview questions about list manipulation and recursion.
Alternatively, a one‑liner using list comprehensions and itertools.chain can be written, but the recursive version is clearer for educational purposes.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500