0
0
NumPydata~5 mins

flatten() and ravel() for 1D conversion in NumPy

Choose your learning style9 modes available
Introduction

We use flatten() and ravel() to turn multi-dimensional arrays into a simple list of values. This helps us look at or work with all data in one line.

When you want to see all numbers in a matrix as a single list.
When you need to prepare data for a function that only accepts 1D input.
When you want to simplify complex data shapes for easier calculations.
When you want to quickly check or print all elements in an array.
When you want to convert image pixel data into a single row for analysis.
Syntax
NumPy
array.flatten()
array.ravel()

flatten() always makes a new copy of the data.

ravel() tries to give a view (no copy) if possible, so it's faster and uses less memory.

Examples
This makes a new 1D array from arr with all elements in order.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
flat_arr = arr.flatten()
This creates a 1D view of arr if possible, sharing the same data.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
raveled_arr = arr.ravel()
Changing raveled_arr changes arr because ravel() returns a view.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
raveled_arr = arr.ravel()
raveled_arr[0] = 10
print(arr)
Changing flat_arr does NOT change arr because flatten() returns a copy.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
flat_arr = arr.flatten()
flat_arr[0] = 10
print(arr)
Sample Program

This program shows how flatten() and ravel() convert a 2D array to 1D. It also shows that changing the raveled array changes the original, but changing the flattened array does not.

NumPy
import numpy as np

# Create a 2D array
arr = np.array([[5, 6, 7], [8, 9, 10]])

# Use flatten() to get a 1D copy
flat = arr.flatten()

# Use ravel() to get a 1D view
rav = arr.ravel()

print('Original array:')
print(arr)

print('\nFlattened array (copy):')
print(flat)

print('\nRaveled array (view):')
print(rav)

# Change first element in raveled array
rav[0] = 100
print('\nAfter changing raveled array first element to 100:')
print('Original array:')
print(arr)

# Change first element in flattened array
flat[0] = 200
print('\nAfter changing flattened array first element to 200:')
print('Original array:')
print(arr)
OutputSuccess
Important Notes

Use flatten() when you want a safe copy and won't change the original array.

Use ravel() for faster operations when you want to save memory and don't mind changes affecting the original.

Both methods return arrays in row-major order (left to right, top to bottom).

Summary

flatten() makes a new 1D copy of the array.

ravel() returns a 1D view if possible, sharing data with the original.

Use these to simplify multi-dimensional data into one line for easier work.