Last modified: Aug 14, 2026

Python Array Flatten: 1D from Multi-Dimensional

Working with multi-dimensional arrays is common in Python. But sometimes you need a simple one-dimensional list. This is called flattening. It simplifies data processing and analysis.

This guide shows you several methods to flatten arrays. You will learn pure Python techniques and the powerful NumPy library. Each method has clear examples.

Flattening is useful for many tasks. You might need it for machine learning features or data visualization. It helps when a function expects a flat list. Let's explore the best ways to do it.

Why Flatten Arrays in Python?

Multi-dimensional arrays store data in rows and columns. This is great for matrices or tables. But many algorithms need a single list of values.

For example, you may want to calculate the sum of all elements. Or you need to pass data to a plot function. Flattening makes these operations straightforward.

Python offers multiple ways to achieve this. The best method depends on your data structure. We will cover simple lists and NumPy arrays.

Method 1: Using Nested List Comprehension

List comprehensions are concise and Pythonic. They are perfect for flattening lists of lists. This method works well for regular nested lists.

Here is how to flatten a 2D list. We iterate over each sublist and then each item. The result is a new flat list.


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

# Flatten using nested list comprehension
flat_list = [item for sublist in matrix for item in sublist]

print(flat_list)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

The comprehension reads from left to right. The first for loop gets each sublist. The second for loop gets each item. This is efficient and fast.

This method works for any depth if you nest more loops. But it becomes messy for very deep arrays. For 3D arrays, you need three loops.

Method 2: Using itertools.chain

The itertools module provides powerful tools. The chain function is perfect for flattening. It treats multiple sequences as one.

You can use chain.from_iterable() for a clean solution. It takes an iterable of iterables. It then returns a single iterator.


from itertools import chain

# Example 2D list
data = [[10, 20], [30, 40], [50, 60]]

# Flatten using itertools.chain
flat_data = list(chain.from_iterable(data))

print(flat_data)

[10, 20, 30, 40, 50, 60]

The chain.from_iterable() method is efficient. It avoids creating intermediate lists. This is great for large datasets.

You can also use chain(*data) but it is less efficient. The * operator unpacks the list. This can cause memory issues with huge lists.

Method 3: Using NumPy's flatten()

NumPy is the standard for numerical computing. It offers the flatten() method. This is the fastest way to flatten arrays.

This method works on NumPy arrays. It always returns a copy of the data. The result is a 1D array.


import numpy as np

# Create a 2D NumPy array
array_2d = np.array([[1, 2], [3, 4], [5, 6]])

# Flatten using NumPy's flatten() method
flat_array = array_2d.flatten()

print(flat_array)
print(type(flat_array))

[1 2 3 4 5 6]

The flatten() method is simple and fast. It is optimized for performance. It handles very large arrays efficiently.

NumPy also has the ravel() method. It returns a flattened view when possible. This can save memory but modifies the original array. Use flatten() for safety.

If you are comparing arrays, check our Python Array Comparison Guide for useful tips.

Method 4: Flattening with Recursion

Nested lists can have varying depths. For example, [1, [2, [3, 4]], 5]. Recursion handles this perfectly. It flattens all levels.

We define a function that processes each element. If it is a list, we recurse. Otherwise, we add it to the result.


def flatten_recursive(nested_list):
    """Flatten a deeply nested list."""
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten_recursive(item))
        else:
            result.append(item)
    return result

# Example with uneven nesting
nested = [1, [2, [3, 4]], 5, [6, [7, [8]]]]
flat = flatten_recursive(nested)

print(flat)

[1, 2, 3, 4, 5, 6, 7, 8]

This recursive approach works for any depth. It is elegant but can be slow for huge lists. Use it when you have irregular nested structures.

Be careful with recursion depth. Python has a limit of about 1000. For very deep lists, you might hit this limit.

Performance Comparison

Which method is fastest? It depends on the data size. For small lists, list comprehensions are fine. For large lists, itertools is better.

For NumPy arrays, flatten() is unbeatable. It is written in C and optimized. It is much faster than pure Python loops.

Here is a simple performance test. We create a large 2D list and time each method.


import time
import itertools
import numpy as np

# Large dataset
big_list = [[i for i in range(100)] for _ in range(1000)]

# Test list comprehension
start = time.time()
flat_comp = [item for sublist in big_list for item in sublist]
print(f"List comprehension: {time.time() - start:.4f} seconds")

# Test itertools
start = time.time()
flat_chain = list(itertools.chain.from_iterable(big_list))
print(f"itertools.chain: {time.time() - start:.4f} seconds")

# Test NumPy
big_array = np.array(big_list)
start = time.time()
flat_np = big_array.flatten()
print(f"NumPy flatten: {time.time() - start:.4f} seconds")

List comprehension: 0.0012 seconds
itertools.chain: 0.0009 seconds
NumPy flatten: 0.0003 seconds

NumPy is clearly the fastest. But it requires converting to an array first. For pure Python, itertools wins.

If you are working with arrays often, consider learning more about Python Array vs NumPy Array to make the right choice.

Common Mistakes to Avoid

One common mistake is using sum(list_of_lists, []). This works but is very slow. Avoid it for large arrays.

Another mistake is modifying the original array. The flatten() method returns a copy. The ravel() method might return a view. Know the difference.

Also, remember that strings are iterable. Flattening a list with strings will break them into characters. Ensure your data is homogeneous.


# Bad example with strings
mixed = ["ab", "cd"]
# This will break strings
flat_bad = [char for s in mixed for char in s]
print(flat_bad)

# Correct way
flat_good = [s for s in mixed]
print(flat_good)

['a', 'b', 'c', 'd']
['ab', 'cd']

Always check your data type. Flattening is for numeric or object arrays, not for strings.

For more array operations, see our Python Array Functions Guide.

Practical Use Cases

Flattening is used in image processing. A 2D pixel grid becomes a 1D feature vector. This is essential for machine learning models.

It is also used in data analysis. You might have a list of rows from a CSV file. Flattening helps you compute global statistics.

In web development, you might flatten nested JSON data. This makes it easier to store in a database. The techniques are the same.

Here is a real-world example with a list of coordinates:


# List of (x, y) coordinates
points = [(1, 2), (3, 4), (5, 6)]

# Flatten to [x1, y1, x2, y2, ...]
flat_points = [coord for point in points for coord in point]
print(flat_points)

[1, 2, 3, 4, 5, 6]

This is useful for plotting libraries. Many expect flat coordinate arrays.

Conclusion

Flattening arrays is a fundamental skill in Python. You have several powerful methods to choose from. Start with list comprehensions for simple cases.

For large pure Python lists, use itertools.chain. For numerical data, always use NumPy's flatten(). It is fast and reliable.

Recursion is your friend for deeply nested structures. Just be mindful of depth limits. Each method has its place.

Practice with your own data. Test different methods to see which works best. Flattening will become second nature.

Remember to choose the right tool for your task. This will make your code cleaner and faster. Happy coding!