+3 votes
in Programming Languages by (19.3k points)
Is there any Python function to reverse the contents of an array/list along an axis?

E.g.

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

to

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

1 Answer

0 votes
by (33.7k points)

You can use NumPy’s flip() function to reverse the contents of an array. If you have a 2D array, you can specify the axis. If you do not specify the axis, the function will reverse the contents along all of the axes.

Examples:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8])
>>> np.flip(a)
array([8, 7, 6, 5, 4, 3, 2, 1])

>>> b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

>>> b
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.flip(b)

array([[12, 11, 10,  9],
       [ 8,  7,  6,  5],
       [ 4,  3,  2,  1]])

>>> np.flip(b,axis=0)
array([[ 9, 10, 11, 12],
       [ 5,  6,  7,  8],
       [ 1,  2,  3,  4]])

>>> np.flip(b,axis=1)
array([[ 4,  3,  2,  1],
       [ 8,  7,  6,  5],
       [12, 11, 10,  9]])

...