0% found this document useful (0 votes)
2 views2 pages

Sorting Arrays

Sorting arrays is essential for data analysis, and Python offers the sort() and sorted() functions for this purpose. The sort() method sorts an array in-place and can be customized using the key and reverse parameters. Examples illustrate sorting integers, strings, and 2-D arrays based on specific elements.

Uploaded by

Sj Je
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Sorting Arrays

Sorting arrays is essential for data analysis, and Python offers the sort() and sorted() functions for this purpose. The sort() method sorts an array in-place and can be customized using the key and reverse parameters. Examples illustrate sorting integers, strings, and 2-D arrays based on specific elements.

Uploaded by

Sj Je
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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]]

You might also like