{"id":5872,"date":"2021-05-16T10:43:41","date_gmt":"2021-05-16T05:13:41","guid":{"rendered":"https:\/\/python-programs.com\/?p=5872"},"modified":"2021-11-22T18:42:37","modified_gmt":"2021-11-22T13:12:37","slug":"how-to-reverse-a-1d-2d-numpy-array-using-np-flip-and-operator-in-python","status":"publish","type":"post","link":"https:\/\/python-programs.com\/how-to-reverse-a-1d-2d-numpy-array-using-np-flip-and-operator-in-python\/","title":{"rendered":"How to Reverse a 1D & 2D numpy array using np.flip() and [] operator in Python"},"content":{"rendered":"

Reversing a 1D and 2D numpy array using np.flip() and [] operator in Python.<\/h2>\n

Reverse 1D Numpy array using ‘[]’ operator :<\/h3>\n

By not passing any start or end parameter, so by default complete array is picked. And as step size is -1, so elements selected from last to first.<\/p>\n

# Program :\r\n\r\nimport numpy as sc\r\n\r\n# Creating a numpy array\r\nnum_arr = sc.array([11,22,33,44,55,66])\r\n\r\nprint('Original Array: ',num_arr)\r\n\r\n# To get reverse of numpy array\r\nrev_arr = num_arr[::-1]\r\n\r\nprint('Reversed Array : ', rev_arr)<\/pre>\n
Output :\r\nOriginal Array:\u00a0 [11 22 33 44 55 66]\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \r\nReversed Array :\u00a0 [66 55 44 33 22 11]<\/pre>\n

Reverse Array is View Only :<\/h3>\n

Here if we do any modification in reversed array, it will also be reflected in original array.<\/p>\n

# Program :\r\n\r\nimport numpy as sc\r\n\r\n# Creatin a numpy array\r\nnum_arr = sc.array([11,22,33,44,55,66])\r\n\r\n# To get reverse of numpy array\r\nrev_arr = num_arr[::-1]\r\nrev_arr[4]=63\r\n\r\nprint('Modified reversed Array : ', rev_arr)\r\nprint('Original array is: ',num_arr)<\/pre>\n
Output :\r\nModified reversed Array :\u00a0 [66 55 44 33 63 11]\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \r\nOriginal array is:\u00a0 [11 63 33 44 55 66]<\/pre>\n

Reverse Numpy array using np.flip() :<\/h3>\n

flip()<\/code> function provided by Python’s numpy module helps to flip or reverse the content of numpy array.<\/p>\n

Syntax : numpy.flip(arr, axis=None)<\/pre>\n

where,<\/p>\n