PYTHON

Flattening a List of Lists (Nested Lists)

Learn how to transform a nested list structure into a single, flat list in Python, a common operation when dealing with varied data sources.

def flatten_list_of_lists(nested_list):
    flat_list = []
    for sublist in nested_list:
        for item in sublist:
            flat_list.append(item)
    return flat_list

# Using list comprehension (more concise):
def flatten_list_comprehension(nested_list):
    return [item for sublist in nested_list for item in sublist]

# Example usage:
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

flattened_manual = flatten_list_of_lists(matrix)
print(f"Original nested list: {matrix}")
print(f"Flattened using loops: {flattened_manual}")

flattened_comprehension = flatten_list_comprehension(matrix)
print(f"Flattened using list comprehension: {flattened_comprehension}")
How it works: This snippet shows two common ways to flatten a list of lists (or nested list) into a single, one-dimensional list. The first method uses nested loops, iterating through each sublist and then each item within the sublist to append it to a new flat list. The second method demonstrates a more Pythonic and concise approach using a nested list comprehension, achieving the same result in a single line. Both methods are effective for unwrapping nested data structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs