PYTHON
Flatten a List of Lists Using List Comprehension
Discover how to efficiently flatten a nested list (list of lists) into a single, flat list in Python using a concise and readable list comprehension.
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flat_list_comprehension = [item for sublist in nested_list for item in sublist]
print("Flattened list (comprehension):", flat_list_comprehension)
# For more complex nested structures or varying depths, consider recursion
# Example with map and sum (less efficient for large lists)
# flat_list_sum = sum(nested_list, [])
# print("Flattened list (sum):", flat_list_sum)
How it works: This code snippet illustrates how to flatten a list of lists into a single, one-dimensional list. The most Pythonic and efficient method shown is using a nested list comprehension, which iterates through each sublist and then through each item within those sublists, collecting them into a new flat list. This is useful for processing data that might come in a grouped or segmented format from APIs or other data sources.