Sorting and Reversing Sequences
Learn how to use Python's built-in sorted() and reversed() functions to create sorted and reversed copies of any iterable.
Python's built-in sorted() function takes any iterable and returns a new sorted list — without touching the original.
Here, we sort a list of numbers:
The basic syntax of sorted():
sorted() works on any iterable, including strings and tuples:
What will be the output?
Pass reverse=True to sort in descending order.
Sorting the same list in descending order:
What will be the output?
Importantly, sorted() never modifies the original iterable. It always returns a brand-new list.
The original list stays unchanged:
What will be the output?
The reversed() function returns an iterator that yields items from a sequence in reverse order.
Wrap reversed() in list() to see the result:
You can also iterate over reversed() directly in a for-loop:
What will be the output?
What will be the output?
What will be the output?
What will be the output?