On this page
sorted
Prev: slice | Up: __builtins__ | Next: staticmethod
Rel: all, any, enumerate, filter, iter
Ref: docs.python.org — sorted
Tags: #public #python3 #builtins
Import & Availability
# Built-in (available globally without import)
from builtins import sorted
Overview & Signature
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
Usage
words = ["pear", "fig", "apple"]
assert sorted(words, key=len) == ["fig", "pear", "apple"]
assert words == ["pear", "fig", "apple"] # original list is untouched
Gotchas
- Always returns a new
list(never mutates the input) and is guaranteed stable (Timsort preserves original relative order of ties). - Use
list.sort()when you want to sort a list in place without allocating a copy.
REPL Inspect
help(sorted)
Linked from
Related notes
- tuts/python3/__builtins__/__builtins__ Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/slice Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/staticmethod Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__ links to this page; shared tags: #builtins
- tuts/python3/__builtins__/all Linked here; shared tags: #builtins
- tuts/python3/__builtins__/any Linked here; shared tags: #builtins
- tuts/python3/__builtins__/enumerate Linked here; shared tags: #builtins
- tuts/python3/__builtins__/filter Linked here; shared tags: #builtins
- tuts/python3/__builtins__/iter Linked here; shared tags: #builtins
- tuts/c/builtins shared tags: #builtins