# Flip a NumPy array in Python

In this tutorial, we will learn how to flip a NumPy array in Python.

## What is Flip in NumPy

The very first part of this tutorial is the basic definition of Flip:-

Flip in NumPy means to reverse the order of elements along the specified axis without changing the shape of the array.

For this task, we need to import NumPy module as:

`import numpy as np`

After that, we will make an array of 27 elements and reshape it with parameters as (3,3,3). The snippet for making the array is:

arr = np.arange(27).reshape((3, 3, 3))

So, let’s have a look into the array, and then we will try to flip it.

print("Array before flipping: \n", arr)

So, you might have guessed the output array if you know about the arange and reshape function. The output looks like:

Array before flipping : [[[ 0 1 2] [ 3 4 5] [ 6 7 8]]

[[ 9 10 11] [12 13 14] [15 16 17]]

[[18 19 20] [21 22 23] [24 25 26]]]

This is our original array. Now, flipping enters into the context. We already have discussed the definition, now we will have a look at its implementation:

The syntax of flip is:

np.flip(array, axis)

NumPy is imported as np.

The array is the input array.

The axis is the specified axis to reverse the array elements. It is an integer that defines the axis or axes to reverse the elements. By default where axis=None, all the axis will be reversed.

Note: axis = 0 will flip axis vertically and axis = 1 will flip axis horizontally.

Now, let’s flip the array using NumPy.flip as:

print("Array after flipping : \n", np.flip(arr))

As we have understood the functioning of the code. Now, we shall run the code to see if we have successfully flipped our array or not.

So, the overall code is:

import numpy as np arr = np.arange(27).reshape((3, 3, 3)) print("Array before flipping : \n", arr) print("Array after flipping : \n", np.flip(arr))

Output looks like:

Array before flipping : [[[ 0 1 2] [ 3 4 5] [ 6 7 8]]

[[ 9 10 11] [12 13 14] [15 16 17]]

[[18 19 20] [21 22 23] [24 25 26]]] Array after flipping : [[[26 25 24] [23 22 21] [20 19 18]]

[[17 16 15] [14 13 12] [11 10 9]]

[[ 8 7 6] [ 5 4 3] [ 2 1 0]]]

So here we have accomplished our task to reverse the order of elements in an array. You can give a try to reverse axis = 0 and also axis = 1 for better understanding.

Thanks for reading. Feel free to comment and share your reviews.

## Leave a Reply