Python Sort Array Values

Use np.sort() to sort array values in an ordered sequence in Python. By using this you can sort an N-dimensional array of any data type. This function gives a sorted copy of the source array or input array without modifying the input array.

Note that Python language doesn’t have an array type but you can use the NumPy library to use arrays in Python. This article explains how to create and sort NumPy array.

If you are looking to sort a list or set, refer to sorting list in python or sorting sets in python.

1. Quick Examples of Sorting Arrays in Python

If you are in a hurry, below are some quick examples of how to sort array values in python.


# Quick examples of sorting arrays 

# Example 1: Sort in ascending order
array = np.array([5,8,6,12,3,15,1])
sorted_array = np.sort(array)

# Example 2: Sort in descending order
array = np.array([5,8,6,12])
array[::-1].sort()

# Example 3: Use numpy.ndarray.sort()
array_copy = np.sort(array)[::-1]

2. Syntax of Array sort()

Following is the syntax of the numpy array sort(). The sort() returns a sorted copy of the input array, which is having the same shape and same type as an input.


# Syntax of NumPy array sort()
numpy.sort(arr, axis= -1, kind=None, order=None)

2.1 Parameter of sort()

This function allows four Parameters.

  • arr: Array to be sorted.
  • axis: This parameter defines the axis along which sorting is performed. If this parameter is None, the array will be flattened before sorting, and by default, this parameter is set to -1, which sorts the array along with the last axis.
  • order: This parameter specifies which fields to compare first.
  • kind : [‘quicksort’{default}, ‘mergesort’, ‘stable’, ‘heapsort’]Sorting algorithm.

3. Python Sort Array Example

Use numpy.sort() function to sort the elements of an array in an ordered sequence in Python. The parameter arr is mandatory. If you execute this function on a one-dimensional array, it will return a one-dimensional sorted array containing elements in ascending order.

In order to use NumPy, first, you need to install it and import it by using import numpy as np.


# Import NumPy module
import numpy as np

# Create NumPy array
array = np.array([5,8,6,12,3,15,1])
print("Original array:",array)

# Sort in ascending order
sorted_array = np.sort(array)
print("Sorted ascending order:",sorted_array)

Yields below output.

python sort array values

From the above code, it returned a sorted copy of the NumPy array, but the original NumPy remains unchanged.

4 Sort Array in Descending Order

By default numpy.sort() function sorts the NumPy array in ascending order. Let’s see how to sort NumPy arrays in descending order.

Sorting a NumPy array in descending order sorts the elements from largest to smallest value. You can use the syntax array[::-1] to reverse the array.


# Sort array in descending order
array = np.sort(array)[::-1]
print("Sorted descending order:\n",array)

# Output
# Sorted descending order:
#  [15 12  8  6  5  3  1]

5. Sort String Arrays

Use this function to sort arrays of different data types like an array of strings, a boolean array, etc. When you sort an array with characters, it sorts in alphabetical order.


# Create NumPy array
array = np.array(["A","Z","X","M"])
print(array)

# Sort string of arrays
array = np.sort(array)
print(array)

# Output:
# ['A' 'Z' 'X' 'M']
# ['A' 'M' 'X' 'Z']

Frequently Asked Questions on Python Sort Array Values

How do I sort an array in Python?

You can use the sorted() function or the sort() method. The sorted() function returns a new sorted list, while the sort() method sorts the list in place.

Can I sort the array in descending order?

You can use the reverse parameter with sorted() or sort() to sort in descending order.

How can I sort without modifying the original array?

If you want to keep the original array unchanged, use sorted() and store the result in a new variable.

Are there other sorting algorithms available in Python?

Python’s built-in sorting functions primarily use an algorithm called Timsort, which is a hybrid sorting algorithm derived from merge sort and insertion sort. The sorted() and sort() functions use this algorithm.

What if my array contains custom objects or complex data structures?

You can use the key parameter in sorted() or sort() to specify a function that returns a value by which to sort the objects.

Conclusion

In this article, I have explained how to sort arrays using the numpy.sort() function in Python. And also I have explained how to sort string, number values by ascending and descending order.

Happy Learning!!

Related Articles

References

Naveen

Naveen (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn LinkedIn

Leave a Reply