Back to Python
2026-03-225 min read

JS Sort Numeric Array (Python Programming)

Learn JS Sort Numeric Array (Python Programming) step by step with clear examples and exercises.

Why This Matters

Sorting arrays is an essential operation in programming as it helps manage and analyze data efficiently. In this lesson, we will focus on sorting numeric arrays in Python. Understanding how to sort numeric arrays can help you solve real-world problems, prepare for interviews, and avoid common pitfalls.

Prerequisites

To follow this lesson, you should be familiar with the following:

  1. Basic Python syntax, including variables, data types, and operators
  2. Control structures like loops and conditionals (if/else)
  3. List comprehensions in Python
  4. Functions and function definitions
  5. Understanding of sorting algorithms and their time complexities

Core Concept

Python provides several methods to sort numeric arrays:

  1. sort() method for lists
  2. sorted() function for both lists and other iterable objects
  3. Using the heapq module's heapsort() function
  4. Custom sorting functions (for more complex requirements)

Sorting with the sort() method

The most straightforward way to sort a list in Python is by using the built-in sort() method:

numbers = [5, 3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4, 5]

The sort() method modifies the list it is called upon and returns None. The sorting is done in-place and is stable (meaning that equal elements maintain their original order).

Sorting with the sorted() function

Unlike the sort() method, the sorted() function can be used on any iterable object and returns a new sorted list:

numbers = [5, 3, 1, 4, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4, 5]
print(numbers) # Output: [5, 3, 1, 4, 2]

Sorting with the heapq.heapsort() function

The heapq module provides an efficient sorting algorithm called heapsort. Heapsort is useful for large lists and has a better average-case time complexity than the built-in sorting methods:

import heapq
numbers = [5, 3, 1, 4, 2]
heapq.heapsort(numbers)
print(numbers) # Output: [1, 2, 3, 4, 5]

Custom sorting functions

For more complex requirements where the default sorting order is not sufficient, you can define custom sorting functions that take two elements and return -1, 0, or 1 based on whether the first element should come before, be equal to, or after the second element:

def custom_sort(a, b):
if a > b:
return 1
elif a < b:
return -1
else:
return 0

numbers = [5, 3, 1, 4, 2]
numbers.sort(key=custom_sort)
print(numbers) # Output: [1, 2, 3, 4, 5]

Worked Example

Let's consider a list of mixed data types and sort only the numeric elements using the sort() method:

mixed_data = [5, 'apple', 3, 'banana', 1, 'orange', 4]
numbers = []
for element in mixed_data:
if isinstance(element, (int, float)):
numbers.append(element)
numbers.sort()
print(numbers) # Output: [1, 3, 4, 5]

Common Mistakes

Forgetting to sort in-place

When using the sort() method, remember that it modifies the list it is called upon and returns None. If you want to store the sorted list in a variable, make sure to assign the result back to the original list:

numbers = [5, 3, 1, 4, 2]
sorted_numbers = numbers.sort() # This is incorrect!
print(numbers) # Output: [3, 1, 4, 2, 5]

numbers.sort()
print(numbers) # Output: [1, 2, 3, 4, 5]

Using the sorted() function incorrectly

The sorted() function returns a new sorted list, so if you want to modify the original list, assign the result back to the original list:

numbers = [5, 3, 1, 4, 2]
sorted_numbers = sorted(numbers)
numbers = sorted_numbers # Assign the sorted list to the original list
print(numbers) # Output: [1, 2, 3, 4, 5]

Misusing the heapq.heapsort() function

The heapq.heapsort() function requires a mutable sequence as input. If you pass an immutable list (like a tuple), it will raise a TypeError:

import heapq
numbers = (5, 3, 1, 4, 2) # This is an immutable list
heapq.heapsort(numbers) # Raises a TypeError

To sort an immutable list, first convert it to a mutable list or use the sorted() function:

import heapq
numbers = (5, 3, 1, 4, 2)
list_numbers = list(numbers) # Convert the tuple to a list
heapq.heapsort(list_numbers)
print(list_numbers) # Output: [1, 2, 3, 4, 5]

Practice Questions

  1. Write a Python script that reads a list of integers from the user and sorts them using the sorted() function.
  2. Given a list of mixed data types, write a script that extracts and sorts only the numeric elements using the heapq.heapsort() function.
  3. Write a Python script that takes a list of integers as input and returns the index of the smallest number if it is present in the list. If no such number exists, return -1. Use the sorted() function to solve this problem.
  4. Given a list of integers, write a script that sorts the list using the heapq.heapsort() function and returns the element at the k-th position (0-indexed) in the sorted list for a given value of k.

FAQ

Why does Python's sorting algorithm not always have O(n log n) time complexity?

Python's built-in sorting methods use a hybrid sorting algorithm that combines quicksort and merge sort based on the length of the list. For small lists, quicksort is faster due to its lower overhead, while for larger lists, merge sort has better performance. This approach allows Python's sorting algorithms to achieve an average-case time complexity of O(n log n).

Why does the heapq.heapsort() function have a better average-case time complexity than the built-in sorting methods?

The heapq.heapsort() function uses a heapsort algorithm, which has a worst-case and average-case time complexity of O(n log n). In contrast, quicksort (used by Python's built-in sorting methods) has a worst-case time complexity of O(n^2) when the input is already sorted or reverse-sorted. Heapsort performs better on these types of inputs due to its bottom-up approach.

Can I use the heapq module for sorting strings?

No, the heapq module is designed for sorting numeric data. If you want to sort a list of strings, you can use the built-in sort() method or the sorted() function.

JS Sort Numeric Array (Python Programming) | Python | XQA Learn