← Back to all snippets
PYTHON

Flatten a Nested List Using List Comprehension

Learn a concise and Pythonic way to flatten a list of lists into a single, one-dimensional list using a simple list comprehension, ideal for data processing.

# Example of a nested list
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# Flatten the list using a nested list comprehension
flattened_list = [item for sublist in nested_list for item in sublist]
print(f"Flattened list: {flattened_list}")

# Flattening with a condition (e.g., only even numbers)
conditional_flatten = [item for sublist in nested_list for item in sublist if item % 2 == 0]
print(f"Conditional flatten (evens): {conditional_flatten}")
How it works: This snippet demonstrates how to flatten a list of lists into a single list using a nested list comprehension. This Pythonic construct iterates through each `sublist` in the `nested_list`, and then through each `item` within that `sublist`, effectively collecting all items into a new, flat list. It's a clean and efficient way to handle common data transformation tasks, and can also incorporate conditions for filtering.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs