Working With Iterables

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:

Python
Output

The basic syntax of sorted():

Python

sorted() works on any iterable, including strings and tuples:

Python
Output

What will be the output?

Python

Pass reverse=True to sort in descending order.

Sorting the same list in descending order:

Python
Output

What will be the output?

Python

Importantly, sorted() never modifies the original iterable. It always returns a brand-new list.

The original list stays unchanged:

Python
Output

What will be the output?

Python

The reversed() function returns an iterator that yields items from a sequence in reverse order.

Wrap reversed() in list() to see the result:

Python
Output

You can also iterate over reversed() directly in a for-loop:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python