How to flatten a matrix in Python

Learn how to flatten a matrix in Python. This guide covers various methods, tips, real-world applications, and common debugging techniques.

How to flatten a matrix in Python
Published on: 
Mon
Apr 6, 2026
Updated on: 
Tue
Apr 7, 2026
The Replit Team

A flattened matrix in Python is a single list created from a nested one. This transformation is a frequent task in data science for simpler data management and analysis.

In this article, you'll explore various techniques to flatten matrices. You'll get practical tips, see real-world applications, and receive debugging advice to help you write efficient Python code.

Using numpy.flatten() for simple matrix flattening

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
flattened = matrix.flatten()
print(flattened)--OUTPUT--[1 2 3 4 5 6 7 8 9]

The numpy.flatten() method is a direct way to collapse a multi dimensional NumPy array. After converting the list of lists into a NumPy array with np.array(), you can call matrix.flatten(). This action reads the matrix row by row and returns a new, one dimensional array containing all the elements.

A key detail is that flatten() always returns a copy of the data, so your original matrix remains untouched. It’s a reliable choice when you need to ensure the source data isn't accidentally modified, unlike some other methods that might only provide a view of the array.

Basic flattening techniques

While numpy.flatten() is powerful, Python’s built-in features offer several elegant alternatives for when you're working with standard lists instead of NumPy arrays.

Using list comprehension to flatten a matrix

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print(flattened)--OUTPUT--[1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehension offers a compact and highly readable way to flatten a matrix. It works by nesting two for loops inside a single expression to build the new list.

  • The first loop, for row in matrix, iterates through each sublist.
  • The second loop, for item in row, then pulls out each element from that sublist.

Finally, each item is collected into a new list with a single dimension. This approach is often praised for being "Pythonic"—elegant and efficient for this kind of task.

Using sum() with an empty list as initializer

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = sum(matrix, [])
print(flattened)--OUTPUT--[1, 2, 3, 4, 5, 6, 7, 8, 9]

You can use the built-in sum() function in a clever way to flatten a matrix. By providing an empty list, [], as the second argument, you tell sum() where to start. It then uses the + operator to concatenate each sublist from the matrix onto this starting list, resulting in a single flattened list.

  • It starts with [].
  • Then adds the first row: [] + [1, 2, 3].
  • Then adds the next: [1, 2, 3] + [4, 5, 6], and so on.

While this is a neat trick, it can be less performant than list comprehension for large matrices because it creates intermediate lists during the process.

Flattening with itertools.chain()

import itertools
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = list(itertools.chain(*matrix))
print(flattened)--OUTPUT--[1, 2, 3, 4, 5, 6, 7, 8, 9]

The itertools.chain() function is a highly efficient tool for this job. It works by treating a series of sequences as a single, continuous one. This method is often faster and more memory-friendly than other techniques, especially with very large matrices.

  • The asterisk operator (*) before matrix unpacks the list of lists, feeding each row to chain() as a separate argument.
  • chain() then creates an iterator that yields elements from each row sequentially without creating intermediate lists.
  • Finally, list() consumes this iterator to build the final flattened list.

Advanced flattening operations

For more complex matrices or when memory efficiency is key, you can turn to other specialized NumPy functions and recursive approaches.

Using numpy.ravel() for memory-efficient flattening

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
flattened = matrix.ravel() # Creates a view when possible
print(flattened)--OUTPUT--[1 2 3 4 5 6 7 8 9]

Like flatten(), the numpy.ravel() function collapses a matrix into one dimension. Its main advantage is memory efficiency—it returns a “view” of the original array whenever possible, rather than a copy.

  • A view is a new array that shares the same underlying data. This means any modifications to the flattened array will also change the original matrix.
  • Because it avoids creating a duplicate dataset, ravel() is a great choice when you're optimizing for memory with very large arrays.

Flattening with reshape(-1) in NumPy

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
flattened = matrix.reshape(-1)
print(flattened)--OUTPUT--[1 2 3 4 5 6 7 8 9]

The reshape() method is a versatile NumPy tool for changing an array's dimensions. Using reshape(-1) specifically tells NumPy to flatten the array into a single dimension. The -1 is a handy placeholder that instructs NumPy to automatically calculate the correct length based on the array's total number of elements.

  • Like ravel(), this method is memory-efficient because it often returns a view instead of a copy.
  • Be aware that this means modifications to the flattened array can also alter the original matrix.

Recursive flattening for nested structures

def flatten_nested(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested(item))
else:
flat_list.append(item)
return flat_list

nested_matrix = [[1, 2, [3, 4]], [5, [6, 7]], 8, 9]
print(flatten_nested(nested_matrix))--OUTPUT--[1, 2, 3, 4, 5, 6, 7, 8, 9]

A recursive function is a great solution for flattening lists with unpredictable or deeply nested structures. The flatten_nested function works by calling itself whenever it encounters another list, allowing it to dig through any number of layers to find all the individual elements.

  • The function checks each item using isinstance(item, list).
  • If an item is a list, it calls flatten_nested on that sublist and uses extend() to add the returned elements.
  • If it’s not a list, it simply appends the item.

This makes it a powerful tool for handling complex data structures.

Move faster with Replit

Replit is an AI-powered development platform where you can start coding Python instantly. All the necessary dependencies come pre-installed, so you can skip the setup and focus on building.

While mastering individual techniques is useful, Agent 4 helps you move from piecing together code to building complete applications. It takes your idea and handles the code, databases, APIs, and deployment directly from a description.

  • A data-cleaning utility that takes nested lists from a JSON file and flattens them into a single list for analysis.
  • A playlist consolidator that merges multiple lists of songs into one master playlist.
  • A simple inventory tracker that combines product lists from different suppliers into a unified catalog.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Flattening matrices is usually simple, but a few common issues can trip you up if you're not careful.

Understanding view vs copy with flatten() and ravel()

One of the most important distinctions in NumPy is between a "copy" and a "view." A copy creates an entirely new array with its own data, while a view is just a different way of looking at the original array's data. This difference is key when choosing between flatten() and ravel().

  • The flatten() method always returns a copy. This is safer because any changes you make to the flattened array won't affect your original matrix.
  • The ravel() method returns a view whenever possible. This is more memory-efficient, but be careful—modifying the flattened array will also change the original matrix.

Fixing TypeError when flattening nested structures with mixed types

A TypeError often appears when you try to flatten a list containing both sublists and standalone elements, like [1, [2, 3]]. Methods like list comprehension expect every element to be iterable. When the loop encounters a non-list item (like an integer), it can't iterate over it, which triggers the error.

The best way to handle this is to check each item's type before you process it. A recursive function that uses isinstance() to differentiate between lists and other data types is a robust solution for these irregularly nested structures.

Handling data loss when flattening jagged arrays with NumPy

A jagged array is a list where the inner lists have different lengths, such as [[1, 2], [3, 4, 5]]. If you try to convert this directly into a NumPy array using np.array(), you won't get a 2D array of numbers. Instead, you'll get a 1D array with a dtype=object, where each element is a Python list object.

When you then call flatten() or ravel() on this object array, it doesn't flatten the contents as you'd expect, which can seem like data loss or a bug. To avoid this, use a pure Python method like itertools.chain() or a list comprehension to flatten the jagged list *before* converting it into a NumPy array.

Understanding view vs copy with flatten() and ravel()

One of the most common surprises when using NumPy is how ravel() handles data. Unlike flatten(), which always makes a safe copy, ravel() often creates a "view." This means changes to the flattened array can unexpectedly alter your original matrix.

This behavior can lead to subtle bugs. Take a look at the following code, where modifying the flattened array also changes the source matrix.

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
flattened = matrix.ravel() # Creates a view

# Modify the flattened array, expecting original to stay the same
flattened[0] = 99
print("Original matrix:")
print(matrix) # Original is unexpectedly modified

The code changes the first element of the flattened array to 99. Because ravel() created a view, this modification also alters the original matrix. See how to prevent this behavior in the corrected code below.

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
flattened = matrix.flatten() # Creates a copy

# Modify the flattened array
flattened[0] = 99
print("Original matrix:")
print(matrix) # Original remains unchanged

The fix is to use matrix.flatten(), which creates a completely separate copy of the array's data. Since the new flattened array is independent, changing its values doesn't alter the original matrix. This approach is crucial when you need to protect your source data from accidental modifications. Always opt for flatten() when data integrity is a priority and you want to avoid unexpected side effects in your program.

Fixing TypeError when flattening nested structures with mixed types

While some mixed lists cause a TypeError, others create a more subtle problem. When a matrix contains different data types like numbers and strings, NumPy won't crash. Instead, it will quietly convert everything to a single type, as shown below.

import numpy as np

# A nested list with mixed types
nested_data = [[1, 2], ["a", "b"], [3.5, 4.2]]

# Try to flatten with NumPy
flattened = np.array(nested_data).flatten()
print(flattened) # Returns array of Python objects, not what we want

The np.array() function defaults to an object array when types are mixed, preventing flatten() from accessing the inner elements. The corrected code below shows how to properly flatten this kind of structure.

# For mixed types, use list comprehension
nested_data = [[1, 2], ["a", "b"], [3.5, 4.2]]

flattened = [item for sublist in nested_data for item in sublist]
print(flattened) # Proper flattened list with original types

The fix is a simple list comprehension: [item for sublist in nested_data for item in sublist]. It's a pure Python solution that sidesteps the issues with NumPy's type handling. Instead of getting an object array, you get a clean, flattened list. This method works by looping through each sublist and pulling out every item, preserving their original data types—whether they're numbers, strings, or floats. It's your best bet for mixed-type data.

Handling data loss when flattening jagged arrays with NumPy

Jagged arrays, with rows of varying lengths, can trip up NumPy. Instead of a flat numeric array, np.array() creates an array of objects, preventing functions like flatten() from working as intended. The code below shows this behavior in action.

import numpy as np

# A jagged array (rows of different lengths)
jagged_array = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# NumPy converts it to an array of objects, not a flat numeric array
np_array = np.array(jagged_array)
print(np_array.dtype) # Shows 'object', not int or float
print(np_array) # Not flattened as expected

Because the rows have different lengths, np.array() creates an array of list objects instead of a numeric array. This structure prevents flatten() from accessing and combining the inner elements. The corrected code below shows how to fix this.

import itertools

# A jagged array (rows of different lengths)
jagged_array = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# Use itertools.chain.from_iterable for jagged arrays
flattened = list(itertools.chain.from_iterable(jagged_array))
print(flattened) # Properly flattened list with all numbers

The solution is to use itertools.chain.from_iterable(), a function specifically designed for jagged structures. It treats each sublist as a segment of a single, continuous sequence, sidestepping the NumPy object array issue entirely. Simply wrap the result in list() to get a properly flattened list. Keep this tool in mind whenever you're working with data where rows might have inconsistent lengths, like when parsing messy CSV files or API responses.

Real-world applications

These flattening techniques are essential for preparing data in real-world applications, from analyzing images to training neural networks.

Flattening a grayscale image for feature extraction

In machine learning, a grayscale image represented as a 2D array of pixel values is often flattened into a one-dimensional feature vector with flatten() to prepare it for analysis by an algorithm.

import numpy as np

# Create a small "image" as a 2D array
image = np.array([[120, 80, 200], [50, 180, 90], [255, 30, 60]])
flat_image = image.flatten()
print(f"Original shape: {image.shape}, Flattened shape: {flat_image.shape}")
print(flat_image)

This code transforms a 2D NumPy array, our simple image, into a one-dimensional array. The image.flatten() method is the key here—it takes the 3x3 grid of pixel values and collapses it into a single, continuous sequence.

  • The method reads the elements from the original array row by row.
  • It then arranges them into a new, flat array.

The output confirms this change, showing the array’s shape moving from (3, 3) to (9,). This is a common step for preparing grid-like data for tasks that require a simple list of inputs.

Using reshape() in neural networks for batch processing

When you're processing multiple images at once—a common task in neural networks—reshape() can flatten each image into a feature vector while keeping the batch structure intact.

import numpy as np

# Simulate a batch of 3 small 2x2 grayscale images
batch_images = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
print(f"Batch shape: {batch_images.shape}")

# Flatten each image while preserving the batch dimension
flattened_batch = batch_images.reshape(batch_images.shape[0], -1)
print(f"Flattened batch shape: {flattened_batch.shape}")
print(flattened_batch)

This code uses NumPy’s reshape() method to transform a 3D array of images into a 2D array. The key is how it flattens each individual image while preserving the total number of images in the batch.

  • The first argument, batch_images.shape[0], ensures the number of rows in the new array matches the number of images in the original batch.
  • The -1 is a placeholder that tells NumPy to automatically calculate the column count by collapsing each 2x2 image into a single row of four elements.

The result is a 2D array where each row represents one of the original flattened images.

Get started with Replit

Now, turn these techniques into a real tool with Replit Agent. Describe what you want: “a utility that flattens image pixel data for analysis” or “a script to clean jagged CSV data into one list.”

The Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.