sorted() Sorted new list
Last updated: 2026-09-22
sorted() Sorted new list
sorted(iterable, *, key=None, reverse=False) returns a new sorted list; original unchanged; key and reverse options available.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
sorted(iterable, *, key=None, reverse=False)
⚙️ Parameters
| iterable Required | The iterable to sort. |
|---|---|
| key Optional | Key function applied to each element.(Default:None) |
| reverse Optional | Sort descending when True.(Default:False) |
Returns:A new sorted list; the original is unchanged.
💥 Raises
TypeError— Raised when elements cannot be compared.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
[1, 2, 3]
['apple', 'banana']
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between sorted() and list.sort()?
Asorted() returns a new list, leaves the original unchanged, and works on any iterable; lst.sort() sorts in place, returns None, and only applies to lists.
QAfter sorting, is the original list changed?
ANo. sorted([3, 1, 2]) returns a new list [1, 2, 3] while the original stays [3, 1, 2]; use lst.sort() to sort in place.
QWhat does sorted(lst, key=len, reverse=True) mean?
AIt sorts by string length in descending order: key sets the comparison basis (computed once per element) and reverse=True means descending.
QWhy does sorted([1, 'a']) raise a TypeError?
Aint and str have no defined ordering, so mixed types cannot be sorted; ensure the element types are consistent or provide a key before sorting.