Python Sorting Arrays

Python – Sorting Arrays

Sorting is a fundamental operation in programming, and Python provides several methods to sort arrays efficiently. In this article, we will explore different ways to sort arrays in Python, along with examples to demonstrate their usage.

1. Sorting Arrays using the sorted() Function

The simplest way to sort an array in Python is by using the built-in sorted() function. This function takes an iterable as an argument and returns a new sorted list.

Here’s an example:


numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

The output of this code will be:


[1, 2, 5, 7, 9]

The sorted() function can also be used to sort arrays of strings. In this case, the strings will be sorted in lexicographical order.

2. Sorting Arrays using the sort() Method

In addition to the sorted() function, Python also provides a sort() method that can be used to sort arrays in-place. This means that the original array will be modified.

Here’s an example:


fruits = ['apple', 'banana', 'cherry', 'date']
fruits.sort()
print(fruits)

The output of this code will be:


['apple', 'banana', 'cherry', 'date']

As you can see, the sort() method sorts the array in ascending order. If you want to sort the array in descending order, you can pass the reverse=True argument to the sort() method.


fruits = ['apple', 'banana', 'cherry', 'date']
fruits.sort(reverse=True)
print(fruits)

The output of this code will be:


['date', 'cherry', 'banana', 'apple']

3. Sorting Arrays with Custom Criteria

Sometimes, we may need to sort arrays based on custom criteria. Python allows us to specify a key function that will be used to determine the order of elements.

Here’s an example:


students = [
    {'name': 'Alice', 'age': 20},
    {'name': 'Bob', 'age': 18},
    {'name': 'Charlie', 'age': 22}
]

sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)

The output of this code will be:


[
    {'name': 'Bob', 'age': 18},
    {'name': 'Alice', 'age': 20},
    {'name': 'Charlie', 'age': 22}
]

In this example, we have a list of dictionaries representing students. We use the key=lambda x: x[‘age’] function to specify that the sorting should be based on the ‘age’ key of each dictionary.

Conclusion

Sorting arrays is a common task in programming, and Python provides several methods to accomplish this efficiently. The sorted() function and the sort() method are the most straightforward ways to sort arrays, while the key function allows us to sort arrays based on custom criteria. By understanding and utilizing these methods, you can easily sort arrays in Python for various applications.

Scroll to Top