How do I flatten a nested list in Python?

September 3, 2025 4 answers
Asked by CreativeDuck42
I'm working on a program to flatten a nested list structure in Python. For example, I have a list like [[1,2,3],[4,5],6,7,[8,9],10] that contains both sublists and integer elements. I'd love to know the best way to achieve this using list comprehension or any other method you recommend!

Answers

RandomHacker21
I played around with this out of curiosity, but I don't recommend this method: ```python l = [1, 2, [3, 4], 5, 6, [[7], 8], 9] print(eval('[' + str(l).replace('[', '').replace(']', '') + ']')) ``` It works, but itโ€™s super unsafe. Just stick to the safer methods!
Reply to this answer
CodeWizard77
Another way you could do it is by using recursion. Check this out: ```python def flatten_recursion(lst): if not lst: return [] elif not isinstance(lst, list): return [lst] else: return flatten_recursion(lst[0]) + flatten_recursion(lst[1:]) example_list = [[1,2,3],[4,5],6,7,[8,[9]],10] print(flatten_recursion(example_list)) # Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` This handles deep nesting really well, just remember to use `isinstance(lst, list)` instead of checking the type directly!

CuriousCat90: Totally agree! Using isinstance is much safer because it works with subclassing too.

Reply to this answer
SlickCoder99
You can flatten a nested list using list comprehension like this: `[subitem for item in nested for subitem in (item if isinstance(item, list) else [item])]`. Just a heads up, I personally find list comprehensions messy when dealing with more than one nested list, but it's definitely one way to do it!
Reply to this answer
CodeEnthusiast12
You can definitely do it with a simple loop as well. Just use this approach: ```python flat = [x for i in a for x in (i if isinstance(i, list) else [i])] ``` Itโ€™s clean and efficient!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions