How to invert NumPy array

NumPy is a practical Python library for numerical computing that provides an array object and various mathematical functions.

The numpy.flip() function

We can invert a NumPy array using numpy.flip() function. The numpy.flip() function is used to reverse the order of elements in a NumPy array along a specified axis.

Usage

The numpy.flip() method can reverse the order of elements in a NumPy array along different axes. You can flip arrays horizontally, vertically, or along higher-dimensional axes by specifying the desired axis.

Syntax

Below is the syntax for the numpy.flip() function:

numpy.flip(m, axis=None)
Syntax of numpy.flip() method
  • m is the input array to be flipped.

  • axis (Optional) is the axis that will be used to reverse the array. The array will be flattened if nothing is supplied before being reversed.

Make sure you have the NumPy library installed (you can install it using pip install numpy).

Code examples

Let's have a look at two different code examples explaining the use of numpy.flip():

Flipping a 1-D Array

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
flipped_arr = np.flip(arr)
print("Original array:", arr)
print("Flipped array:", flipped_arr)

Let's understand what happens in the code above:

  • Line 1: Firstly, we import the NumPy module.

  • Line 3: Then, we create a NumPy one-dimensional array to perform the inversion.

  • Line 4: Now, we call np.flip() with the arr array as the argument. This function returns a new array with the elements reversed, which we store in the variable flipped_arr.

  • Line 6–7: Finally, we print the original and inverted arrays to observe the changes.

Flipping a 2-D Array

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
flipped_arr = np.flip(arr, axis=0)
print("Original array:")
print(arr)
print("Flipped array:")
print(flipped_arr)

Let's understand what happens in the code above:

  • Line 1: Firstly, we import the NumPy module.

  • Line 3: Then, we create a NumPy two-dimensional array to perform the inversion.

  • Line 4: Now, we call np.flip() with the arr array as the argument. This function returns a new array with the elements reversed, which we store in the variable flipped_arr.

  • Line 6–9: Finally, we print the original and inverted arrays to observe the changes.

Conclusion

Therefore, inverting a NumPy array can be achieved easily using the numpy.flip() function by reversing the order of elements of the original array along a specified axis. This approach is helpful in various applications, such as rearranging data or performing specific calculations.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved