Home » Python Sorting Arrays (or Lists)

Python Sorting Arrays (or Lists)

Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests

Sorting arrays (or lists) is a common task in programming. Python provides several ways to sort arrays (lists), both in-place and by creating new sorted arrays.

Python supports various sorting techniques using built-in functions and libraries, offering flexibility in sorting based on your requirements.

In this tutorial, we'll cover multiple methods to sort arrays (or lists) in Python using the built-in sort() method, sorted() function, and the NumPy library for more advanced use cases.

1. Using the sort() Method (In-Place Sorting)

The sort() method is used to sort a list in-place, meaning it modifies the original list and does not create a new one. By default, the list is sorted in ascending order.

Example: Sorting a List Using sort()

# Example: Sorting a list using sort()
arr = [50, 20, 30, 10, 40]

# Sort the list in ascending order
arr.sort()

print(arr)  # Output: [10, 20, 30, 40, 50]

In this example:

The sort() method sorts the list in-place, changing the order of elements in the original list.

2. Sorting in Descending Order Using sort()

The sort() method allows you to sort the list in descending order by passing the reverse=True argument.

Example: Sorting a List in Descending Order

# Example: Sorting a list in descending order using sort()
arr = [50, 20, 30, 10, 40]

# Sort the list in descending order
arr.sort(reverse=True)

print(arr)  # Output: [50, 40, 30, 20, 10]

In this example:

The reverse=True argument is passed to sort the list in descending order.

3. Using the sorted() Function (New Sorted List)

The sorted() function returns a new sorted list, leaving the original list unchanged. This is useful when you want to keep the original list intact and only need a sorted version of it.

Example: Using sorted() Function

# Example: Sorting a list using sorted()
arr = [50, 20, 30, 10, 40]

# Get a new sorted list
sorted_arr = sorted(arr)

print("Original:", arr)        # Output: Original: [50, 20, 30, 10, 40]
print("Sorted:", sorted_arr)   # Output: Sorted: [10, 20, 30, 40, 50]

In this example:

The sorted() function returns a new sorted list while keeping the original list unchanged.

4. Sorting in Descending Order Using sorted()

Similar to sort(), the sorted() function can sort a list in descending order by passing the reverse=True argument.

Example: Sorting in Descending Order with sorted()

# Example: Sorting a list in descending order using sorted()
arr = [50, 20, 30, 10, 40]

# Get a new sorted list in descending order
sorted_arr_desc = sorted(arr, reverse=True)

print("Original:", arr)             # Output: Original: [50, 20, 30, 10, 40]
print("Sorted Descending:", sorted_arr_desc)  # Output: Sorted Descending: [50, 40, 30, 20, 10]

In this example:

The reverse=True argument sorts the list in descending order and returns a new sorted list.

5. Sorting Arrays with Custom Key Functions

Both the sort() and sorted() methods allow for custom sorting by passing a key function. The key function defines a custom rule by which the elements should be sorted.

Example: Sorting Based on String Length

# Example: Sorting a list of strings by their length
arr = ["apple", "banana", "kiwi", "cherry", "grape"]

# Sort the list by the length of the strings
arr.sort(key=len)

print(arr)  # Output: ['kiwi', 'grape', 'apple', 'cherry', 'banana']

In this example:

The list of strings is sorted based on the length of each string using key=len.

Example: Sorting with a Custom Function

You can also pass a custom function to the key parameter to sort the list based on a more complex rule.

# Example: Sorting a list of numbers based on their absolute values
arr = [-10, -20, 30, -40, 50]

# Sort by absolute values
arr.sort(key=abs)

print(arr)  # Output: [-10, 30, -20, -40, 50]

In this example:

The list is sorted based on the absolute value of each element using the abs function.

6. Sorting Tuples in a List

When sorting lists of tuples, the first element in each tuple is used for comparison by default. You can also sort based on other elements by specifying a custom key.

Example: Sorting a List of Tuples

# Example: Sorting a list of tuples by the first element
arr = [(3, 'banana'), (1, 'apple'), (2, 'cherry')]

# Sort by the first element of the tuple
arr.sort()

print(arr)  # Output: [(1, 'apple'), (2, 'cherry'), (3, 'banana')]

Example: Sorting a List of Tuples by the Second Element

# Example: Sorting a list of tuples by the second element
arr = [(3, 'banana'), (1, 'apple'), (2, 'cherry')]

# Sort by the second element of the tuple
arr.sort(key=lambda x: x[1])

print(arr)  # Output: [(1, 'apple'), (3, 'banana'), (2, 'cherry')]

In these examples:

By default, the list of tuples is sorted by the first element.
A lambda function is used to sort the list based on the second element of each tuple.

7. Sorting NumPy Arrays

If you're working with NumPy arrays, you can sort them using the np.sort() function. This function returns a sorted copy of the array and works for both 1D and multi-dimensional arrays.

Example: Sorting a 1D NumPy Array

import numpy as np

# Example: Sorting a 1D NumPy array
arr = np.array([50, 20, 30, 10, 40])

# Sort the array
sorted_arr = np.sort(arr)

print(sorted_arr)  # Output: [10 20 30 40 50]

Example: Sorting a 2D NumPy Array

import numpy as np

# Example: Sorting a 2D NumPy array along an axis
arr = np.array([[3, 2, 1], [6, 5, 4]])

# Sort each row of the 2D array
sorted_arr = np.sort(arr, axis=1)

print(sorted_arr)
# Output:
# [[1 2 3]
#  [4 5 6]]

In these examples:

np.sort() sorts the elements of a 1D or 2D NumPy array. You can also specify the axis along which to sort for multi-dimensional arrays.

8. Sorting Strings in Arrays

Python strings are lists of characters, and you can sort a list of strings alphabetically or by a custom rule.

Example: Sorting Strings Alphabetically

# Example: Sorting a list of strings alphabetically
arr = ["banana", "apple", "cherry", "date"]

# Sort the list alphabetically
arr.sort()

print(arr)  # Output: ['apple', 'banana', 'cherry', 'date']

Example: Sorting Strings in Reverse Alphabetical Order

# Example: Sorting strings in reverse alphabetical order
arr = ["banana", "apple", "cherry", "date"]

# Sort the list in reverse alphabetical order
arr.sort(reverse=True)

print(arr)  # Output: ['date', 'cherry', 'banana', 'apple']

In these examples:

The sort() method sorts strings alphabetically by default. You can sort them in reverse alphabetical order using reverse=True.

9. Sorting Arrays with Mixed Data Types

If your array or list contains mixed data types (e.g., integers and strings), sorting will raise an error because Python cannot compare incompatible types directly. It's best to avoid sorting arrays with mixed types.

Example: Sorting an Array with Mixed Types (This Will Raise an Error)

# Example: Sorting an array with mixed types
arr = [1, 'apple', 3, 'banana']

# This will raise a TypeError
# arr.sort()  # Uncommenting this line will raise a TypeError

In this example:

Sorting mixed types will raise a TypeError because Python does not know how to compare strings and integers directly.

Summary

sort(): Sorts a list in-place and modifies the original list.
sorted(): Returns a new sorted list without modifying the original list.
reverse=True: Sorts the list in descending order.
Custom Sorting with key: Allows sorting based on custom criteria, such as string length or absolute value, by passing a function to the key parameter.
NumPy Sorting: Use np.sort() to sort NumPy arrays.
Tuples and Multi-dimensional Arrays: You can sort tuples and multi-dimensional arrays using key functions or np.sort().

By mastering these different sorting techniques, you can efficiently sort arrays or lists in Python to suit your specific needs, whether dealing with simple numeric arrays or complex multi-dimensional data.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More