How to flatten a nested list in Python
Published on Aug. 22, 2023, 12:15 p.m.
To flatten a nested list in Python, you can use various approaches. One simple approach is to use a list comprehension that iterates over the nested lists and adds the elements to a new flattened list. Here is an example:
nested_list = [[1, 2], [3, 4, 5], [6]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)
This will output [1, 2, 3, 4, 5, 6]
.
Alternatively, you can use the itertools
module to chain the nested lists together as follows:
import itertools
nested_list = [[1, 2], [3, 4, 5], [6]]
flattened_list = list(itertools.chain.from_iterable(nested_list))
print(flattened_list)
This will also output [1, 2, 3, 4, 5, 6]
.
These are just a couple of examples of how to flatten a nested list in Python. There are other approaches you can use depending on your specific use case. I hope this helps! Let me know if you have any further questions.