 GFG App
Open App Browser
Continue

# Differences between Flatten() and Ravel() Numpy Functions

We have two similar kinds of ways to convert a ndarray to a 1D array of Flatten() and Ravel() Numpy function in Python programming language.

## Example of Flatten() Numpy function

Here, we will create a Numpy array, and then by using flatten function we have changed the element in the flattened 1D NumPy array.

## Python3

 `import` `numpy as np`   `# Create a numpy array` `a ``=` `np.array([(``1``,``2``,``3``,``4``),(``3``,``1``,``4``,``2``)])`   `# Let's print the array a` `print` `(``"Original array:\n "``, a)`   `# Convert nd array to 1D array` `c ``=` `a.flatten()`   `# Flatten passes copy of` `# original array to 'c'` `print` `(``"\nFlatten array using flatten: "``, c)`

Output:

```Original array:
[[1 2 3 4]
[3 1 4 2]]

Flatten array using flatten:  [1 2 3 4 3 1 4 2]```

The original 2D array is unchanged even if the value of the second member in the flattened 1D Numpy array was changed. This demonstrates that flatten() does return a copy of the Numpy input array.

## Python3

 `c[``2``] ``=` `33`   `print` `(``"Flatten array: "``, c)`   `# Let's print the array a` `print` `(``"\nOriginal array:\n "``, a)`

Output:

```Flatten array:  [ 1  2 33  4  3  1  4  2]

Original array:
[[1 2 3 4]
[3 1 4 2]]```

## Example of ravel() Numpy function

Here, we will create a Numpy array, and then by using the ravel() function we have changed the element in the flattened 1D NumPy array.

## Python3

 `import` `numpy as np`   `# Create a numpy array` `a ``=` `np.array([(``1``,``2``,``3``,``4``),(``3``,``1``,``4``,``2``)])`   `# Let's print the array a` `print` `(``"Original array:\n "``, a)`   `ra ``=` `np.ravel(a)` `print` `(``"\nFlatten array using ravel: "``, ra)`

Output:

````Original array:
[[1 2 3 4]
[3 1 4 2]]

Flatten array using ravel:  [1 2 3 4 3 1 4 2]```

As we can see, The original 2D array is changed if the value of the second member in the flattened 1D Numpy array was changed. This demonstrates that ravel() returns a shallow copy of the Numpy input array.

## Python3

 `ra[``3``] ``=` `44`   `print` `(``"Flatten array: "``, ra)`   `# Let's print the array a` `print` `(``"\nOriginal array:\n "``, a)`

Output:

```Flatten array:  [ 1  2  3 44  3  1  4  2]

Original array:
[[ 1  2  3 44]
[ 3  1  4  2]]```

## Differences between Flatten() and Ravel()

My Personal Notes arrow_drop_up