How to Sort Arrays in Python?

Estimated read time 2 min read

To sort arrays in Python, you can use the sort() method of the NumPy library. The sort() method can be used to sort arrays of any shape, including one-dimensional and multi-dimensional arrays.

Here’s an example implementation:

import numpy as np

# Define a one-dimensional array
my_array = np.array([4, 2, 8, 1, 3, 9, 6])

# Sort the array in ascending order
my_array.sort()
print(my_array)  # Output: [1 2 3 4 6 8 9]

# Define a two-dimensional array
my_2d_array = np.array([[4, 2, 8], [1, 3, 9], [6, 5, 7]])

# Sort the rows of the array in ascending order
my_2d_array.sort(axis=1)
print(my_2d_array)

In this example, we define a one-dimensional array my_array and a two-dimensional array my_2d_array. We use the sort() method to sort my_array in ascending order, and then print the sorted array. We also use the sort() method with the axis=1 argument to sort the rows of my_2d_array in ascending order, and then print the sorted array.

Note that the sort() method sorts the array in place, meaning that it modifies the original array. If you want to create a new sorted array instead, you can use the sorted() function of the built-in list type:

# Create a new sorted array
my_sorted_array = sorted(my_array)
print(my_sorted_array)  # Output: [1, 2, 3, 4, 6, 8, 9]

In this example, we use the sorted() function to create a new sorted array my_sorted_array based on the values of my_array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply