NumPy flip()

The flip() method reverses the order of the elements in an array.


flip() Syntax

The syntax of flip() is:

numpy.flip(array, axis = None)

flip() Arguments

The flip() method takes two arguments:

  • array - an array with elements to be flipped
  • axis(optional) - axis to flip ( None or int or tuple )

flip() Return Value

The flip() method returns the array with elements reversed.


Example 1: Flip a 2-D Array

A 2-D array can be flipped on two axes. If the array is flipped on axis 0, it is reversed vertically and if the array is flipped on axis 1, it is reversed horizontally.

Output

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

Array flipped along axis 0
[[6 7 8]
[3 4 5]
[0 1 2]]

Array flipped along axis 1
[[2 1 0]
[5 4 3]
[8 7 6]]

Here, we haven't passed axis in array2, so the array is flattened, flipped, and reshaped back to its original shape.


Example 2: Flip a 3-D Array on Multiple Axes

Output

Array flipped on axis 0: 
[[[4 5]
  [6 7]]

 [[0 1]
  [2 3]]]

Array flipped on axis 1: 
[[[4 5]
 [6 7]]

 [[0 1]
  [2 3]]]

Array flipped on axes 0 and 1: 
[[[6 7]
  [4 5]]

 [[2 3]
  [0 1]]]

Example 3: Flip with flipup() and fliplr()

Instead of using the axis parameter, we can simply use flipud() to flip vertically and fliplr() to flip horizontally.

Output

Array flipped vertically : 
[[2 3]
 [0 1]]

Array flipped horizontally : 
[[1 0]
 [3 2]]