Home >Backend Development >Python Tutorial >How to Flatten Nested Lists Using List Comprehensions?
Flattening Nested Lists via List Comprehension
When using list comprehensions to transform each element of a list into a list, you may encounter situations where you desire a flattened result instead of a nested list.
For instance, consider a list A and a function f that, when applied to elements in A, return lists. Using a list comprehension, you can obtain a list of lists:
result = [f(a) for a in A]
However, if you seek a flattened list, you can utilize nested iterations within a single list comprehension:
flat_result = [filename for path in dirs for filename in os.listdir(path)]
This comprehension, functionally equivalent to a nested iteration, achieves the desired flattening.
The above is the detailed content of How to Flatten Nested Lists Using List Comprehensions?. For more information, please follow other related articles on the PHP Chinese website!