Programming often requires sorting data, and Python’s built-in sort() function simplifies this task by allowing for quick and efficient sorting of lists. However, the sort() function in Python goes beyond basic sorting abilities. This article will examine some of the distinct capabilities of the s...
Programming often requires sorting data, and Python’s built-in sort() function simplifies this task by allowing for quick and efficient sorting of lists. However, the sort() function in Python goes beyond basic sorting abilities. This article will examine some of the distinct capabilities of the sort() function and demonstrate how to use them to optimize programming tasks.
Size: 956.42 KB
Language: en
Added: May 15, 2023
Slides: 8 pages
Slide Content
Sort() Function in Python Unlocking the Power of Sorting Lists AM – May 2023
Outline Basic Usage Sorting by Key Sorting Complex Object In-Place vs Non-In-Place Sorting
sort ( key=None , reverse=False ) “This method sorts the list in place, using only < comparisons between items . Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state)” -https:// docs.python.org - Parameter Description Reverse Optional. reverse=True will sort the list descending. Default is reverse=False Key Optional. A function to specify the sorting criteria(s) Source: https://www.w3schools.com
Basic Usage The sort() function is used to sort a list in ascending or descending order.
Sorting by Key A key is a function that takes an element in the list as an argument and returns a value that is used for sorting
Sorting Complex Object The sort() function can also be used to sort complex objects, such as dictionaries and tuples, by specifying a key function # Sorting a list of dictionaries by a specific key people = [{ "name" : "Alice" , "age" : 25 }, { "name" : "Bob" , "age" : 18 }, { "name" : "Charlie" , "age" : 32 }] people.sort (key= lambda x: x[ "age" ]) print (people) # Output: [{'name': 'Bob', 'age': 18}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 32}] # Sorting a list of tuples by a specific value inventory = [( "apple" , 10 ), ( "banana" , 5 ), ( "orange" , 7 )] inventory.sort (key= lambda x: x[ 1 ], reverse= True ) print (inventory) # Output: [('apple', 10), ('orange', 7), ('banana', 5)]
In-Place vs Non-In-Place Sorting In-place sorting: Modifies the original list Non-in-place sorting: Returns a new sorted list
Sort() Function in Python Unlocking the Power of Sorting Lists AM – May 2023