Sorting arrays
Sorting arrays is a fundamental operation that enhances data analysis and organization, whether
you're arranging numbers, strings, or even complex objects. Python provides built-in methods
like the sort() function for in-place sorting and the sorted() function for creating a new sorted list
from an iterable.
Sort array in Python Using sort() Function
To sort an array in Python, the sort() method is a direct and efficient approach.
Syntax:
[Link](key=None, reverse=False)
Parameters:
key: Optional. A function to execute to decide the order. Default is None.
reverse: Optional. A Boolean value. False will sort ascending, True will sort descending.
Default is False.
Return:
The sort() method doesn't return any value. Instead, it modifies the original array in-place.
Examples:
1. basic example of Python sort() method:
Sort an array of integers.
arr = [5, 3, 8, 6]
[Link]()
print(arr)
Output: [3, 5, 6, 8]
Sort the array alphabetically Sorting an array of strings alphabetically is another common
task. This example demonstrates how to sort an array of strings alphabetically, which is a
straightforward way to sort array in python by character order.
arr = ["Banana", "Cherry", "Apple"]
[Link]()
print(arr)
Output: ['Apple', 'Banana', 'Cherry']
sort() method on a 2-D array: Sorting a 2-D array based on a specific element, such as the
first element of each sub-array, requires a slightly different approach using the key parameter.
This example shows how to sort a 2-D array in Python, focusing on a specified element within
each sub-array to sort array in python effectively.
arr = [[2, 5], [1, 4], [3, 6]]
[Link](key=lambda x: x[0])
print(arr)
Output: [[1, 4], [2, 5], [3, 6]]