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.
flatten() and ravel() for 1D conversion in 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.
arr with all elements in order.import numpy as np arr = np.array([[1, 2], [3, 4]]) flat_arr = arr.flatten()
arr if possible, sharing the same data.import numpy as np arr = np.array([[1, 2], [3, 4]]) raveled_arr = arr.ravel()
raveled_arr changes arr because ravel() returns a view.import numpy as np arr = np.array([[1, 2], [3, 4]]) raveled_arr = arr.ravel() raveled_arr[0] = 10 print(arr)
flat_arr does NOT change arr because flatten() returns a copy.import numpy as np arr = np.array([[1, 2], [3, 4]]) flat_arr = arr.flatten() flat_arr[0] = 10 print(arr)
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.
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)
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).
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.