How do I flatten a nested list in Python?
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
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
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!
Reply to this answer
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
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.
CuriousCat90: Totally agree! Using isinstance is much safer because it works with subclassing too.