Sort() Function in Python.pptx

AkbarezaMuhammad 76 views 8 slides May 15, 2023
Slide 1
Slide 1 of 8
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8

About This Presentation

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


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