How to reverse an array in Python

You can reverse an array in Python with any of the following methods. If you want to learn Python, I highly recommend reading This Book.

Method 1: Reverse an array using Slicing

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([10, 20, 30, 40, 50])

# Reverse an Array
b = a[::-1]

# Display the Reverse Array
print(b)

Output:

[50 40 30 20 10]

Method 2: Reverse an array using np.flip()

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([10, 20, 30, 40, 50])

# Reverse an Array
b = np.flip(a)

# Display the Reverse Array
print(b)

Output:

[50 40 30 20 10]

Method 3: Reverse an array using np.flipud()

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([10, 20, 30, 40, 50])

# Reverse an Array
b = np.flipud(a)

# Display the Reverse Array
print(b)

Output:

[50 40 30 20 10]

Free Learning Resources

Leave a Comment

Your email address will not be published.