GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.geeksforgeeks.org — Python sorted() Function - GeeksforGeeks Python sorted() FunctionLast Updated : 20 Dec, 2025 sorted() function in Python returns a new sorted list from the elements of any iterable, such as a list, tuple, set, or string. It does not modify the original iterable, unlike the sort() method for lists. Let's start with a basic example of sorting a list of numbers in ascending order using the sorted() function.
Output [1, 2, 3, 4] Syntax
Parameters:
Return Type: Returns a new sorted list containing all elements from the iterable according to the given criteria. Sorting in Descending OrderTo sort an iterable in descending order, set the reverse argument to True.
Output [9, 6, 5, 5, 2, 1] Sorting a StringYou can sort the characters of a string and return a list.
Output ['h', 'n', 'o', 'p', 't', 'y'] Explanation: Each character of the string is treated as an element and sorted in ascending (alphabetical) order. Sorting a TupleYou can sort the elements of a tuple using sorted(), which returns a list.
Output [1, 2, 3, 4] Explanation: Tuples are immutable, so sorted() returns a new sorted list, leaving the original tuple unchanged. Sorting using key ParameterThe key parameter is an optional argument that allows us to customize the sort order. 1. Sorting Strings by Length: You can sort a list of strings by their length using the key=len parameter in sorted().
Output ['date', 'apple', 'banana', 'cherry'] Explanation: The key parameter is set to len, which sorts the words by their length in ascending order. 2. Sorting a List of Dictionaries: You can sort a list of dictionaries based on a specific key using sorted() with a lambda function.
Output [{'name': 'Eve', 'score': 78}, {'name': 'Harry', 'score': 85}, {'name': 'Leo', 'score': 91}]
Explanation: key=lambda x: x['score'] specifies that the sorting should be done using the 'score' value from each dictionary Related Articles:Comment Explore |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |