- 1Python aiter() Function – Get Async Iterator in Python
- 2Python all() Function – Check If All Elements Are True
- 3Python anext() Function – Get Next Item from Async Iterator
- 4Python any() Function – Check if Any Element is True
- 5Python ascii() Function – Get ASCII Representation of Objects
- 6Python bin() Function – Convert Integer to Binary String
- 7Python bool() Function – Convert to Boolean
- 8Python breakpoint() Function – Add Debug Points in Your Code
- 9Python bytearray() Function – Create and Modify Binary Data
- 10Python bytes() Function – Create Immutable Byte Objects
- 11Python callable() Function – Check If Object Is Callable
- 12Python chr() Function – Get Character from Unicode Code Point
- 13Python classmethod() Function – Convert Method to Class Method
- 14Python compile() Function – Compile Source Code at Runtime
- 15Python complex() Function – Create Complex Numbers Easily
- 16Python delattr() Function – Delete Attribute from Object
- 17Python dict() Function – Create and Use Dictionaries Easily
- 18Python dir() Function – List Attributes of Objects
- 19Python divmod() Function – Quotient and Remainder in One Go
- 20Python enumerate() Function – Loop with Index Easily
- 21Python eval() Function – Evaluate Expressions from Strings
- 22Python exec() Function – Execute Dynamic Python Code
- 23Python filter() Function – Filter Items in a List
- 24Python float() Function – Convert to Floating Point Number
- 25Python format() Function – Format Strings Easily
- 26Python frozenset() Function – Create Immutable Sets
- 27Python getattr() Function – Access Object Attributes Dynamically
- 28Python globals() Function – Access Global Symbol Table
- 29Python hasattr() Function – Check If an Object Has an Attribute
- 30Python hash() Function – Generate Hash Values of Objects
- 31Python help() Function – Get Help on Python Functions, Classes, and Modules
- 32Python hex() Function – Convert Integer to Hexadecimal
- 33Python id() Function – Get Memory Address of an Object
- 34Python input() Function – Get User Input Easily
- 35Python int() Function – Convert to Integer
- 36Python isinstance() Function – Check Type of a Variable
- 37Python issubclass() Function – Check Class Inheritance
- 38Python iter() Function – Create an Iterator from Iterable
- 39Python len() Function – Get the Length of Strings, Lists, and More
- 40Python list() Function – Convert Data to a List
- 41Python locals() Function – Get Local Symbol Table as a Dictionary
- 42Python map() Function – Apply a Function to Each Element
- 43Python max() Function – Find the Largest Value
- 44Python memoryview() Function – Work With Binary Data Efficiently
- 45Python min() Function – Find the Smallest Value
- 46Python next() Function – Retrieve Next Item from an Iterator
- 47Python object() Function – Base Object Constructor Explained
- 48Python oct() Function – Convert Number to Octal
- 49Python open() Function – Read, Write, and Create Files Easily
- 50Python ord() Function – Get Unicode Code of a Character
- 51Python pow() Function – Raise a Number to a Power
- 52Python print() Function – Print Output to the Console
- 53Python property() Function – Create Managed Attributes
- 54Python range() Function – Generate Number Sequences Easily
- 55Python repr() Function – Get String Representation of an Object
- 56Python reversed() Function – Reverse Iterables Easily
- 57Python round() Function – Round Numbers to Nearest Integer or Decimal Places
- 58Python set() Function – Create a Set from Iterable
- 59Python setattr() Function – Dynamically Set Object Attributes
- 60Python slice() Function – Create Slice Objects for Lists and Strings
- 61Python sorted() Function – Sort Any Iterable Easily
- 62Python staticmethod() Function – Create Static Methods in Classes
- 63Python str() Function – Convert to String Easily
- 64Python sum() Function – Add Items of an Iterable
- 65Python super() Function – Call Parent Class Methods
- 66Python tuple() Function – Create a Tuple from Iterable
- 67Python type() Function – Get the Type of an Object
- 68Python vars() Function – View Object’s Attributes
- 69Python zip() Function – Combine Iterables Element-Wise
- 70Python __import__() Function – Dynamic Module Import
- 71Python str.format() – Format Strings Easily with Placeholders
- 72Python String format_map() – Format Strings with a Mapping
Python sorted() Function – Sort Any Iterable Easily
Python sorted()
Function
The sorted() function in Python is used to sort elements of any iterable (like a list, tuple, or string) and return a new sorted list. It does not modify the original data.
Syntax
sorted(iterable, *, key=None, reverse=False)
Parameters:
iterable
– The sequence to be sorted (like list, tuple, set, dictionary keys, string, etc.)key
(optional) – A function to customize sorting logicreverse
(optional) – IfTrue
, sorts in descending order
Returns:
- A new sorted list.
Example 1: Sorting a List
numbers = [4, 2, 9, 1]
print(sorted(numbers))
[1, 2, 4, 9]
Example 2: Sorting in Reverse Order
numbers = [4, 2, 9, 1]
print(sorted(numbers, reverse=True))
[9, 4, 2, 1]
Example 3: Sorting Strings Alphabetically
fruits = ["banana", "apple", "cherry"]
print(sorted(fruits))
['apple', 'banana', 'cherry']
Example 4: Sorting with a Key Function
# Sort by length of strings
words = ["apple", "banana", "fig", "date"]
print(sorted(words, key=len))
['fig', 'date', 'apple', 'banana']
Example 5: Sorting Tuples by Second Element
pairs = [(1, 3), (2, 2), (4, 1)]
print(sorted(pairs, key=lambda x: x[1]))
[(4, 1), (2, 2), (1, 3)]
Use Cases
- Alphabetical sorting of names or words
- Sorting numbers for comparisons
- Custom sorting using
key
, like sorting objects by attributes - Sorting dictionary keys or values
Common Mistakes
- Expecting
sorted()
to change the original list – it returns a new one - For descending order, forgetting to use
reverse=True
- Passing non-iterable values like integers
Interview Tip
Use sorted()
with custom key
functions to solve problems like sorting students by grades, or sorting tuples by second item.
Summary
sorted()
returns a new sorted list from any iterable- Supports
key
for custom sort logic - Set
reverse=True
for descending order
Practice Problem
Write a program that reads 5 space-separated numbers and prints them in descending order.
nums = list(map(int, input("Enter 5 numbers: ").split()))
sorted_nums = sorted(nums, reverse=True)
print("Sorted descending:", sorted_nums)