Have you ever thought, why there are two functions for transforming multi-dimensional array to one-dimensional array? Which one is best for me? flatten() or ravel(). This tutorial will answer you by comparing them one by one.

Numpy ravel() | Numpy flatten() |
---|---|

`ravel()` function simply returns a flattened view of Numpy array. |
`flatten()` function returns a flattened copy of Numpy array. |

If you try to modify the flattened view then you end up with that same change in the original array. | Changes made to flattened array is not reflected back to the original array. |

`ravel()` does not occupy memory so we can say that it is faster than `flatten()` |
`flatten()` occupies memory so it is considered slower than `ravel()` function. |

Let's understand the second difference with the help of an example-

#Python program to clarify the difference between ravel() and flatten() import numpy as np print('Checking ravel()') x = np.array([[40, 32, 67], [61, 79, 15]]) print('Original array:\n', x) y = x.ravel() print() y[1] = 1000 print('Original array after making changes in flattened array:\n', x) print('\nChecking flatten()') a = np.array([[40, 32, 67], [61, 79, 15]]) print('Original array:\n', a) b = a.flatten() print() b[1] = 1000 print('Original array after making changes in flattened array:\n', a)

Output of the above program

Checking ravel() Original array: [[40 32 67] [61 79 15]] Original array after making changes in flattened array: [[ 40 1000 67] [ 61 79 15]] Checking flatten() Original array: [[40 32 67] [61 79 15]] Original array after making changes in flattened array: [[40 32 67] [61 79 15]]

- How to convert Numpy Array to List?
- What is NumPy ndarray shape in Python?
- What is NumPy axis?
- What are NumPy data types?
- What are structured arrays in Python NumPy?
- What are NumPy array attributes?
- How to iterate over NumPy array?
- What is NumPy arrays broadcasting?
- How to change data type of a given Numpy array?
- How to use NumPy split() in Python?
- How to use NumPy flatten() in Python?
- How to use NumPy ravel() in Python?