Search⌘ K
AI Features

Puzzle 8: Explanation

Explore how Python's reversed function returns an iterator and understand its behavior with sorted calls. Learn why consuming the iterator once results in an empty output on a second call and how StopIteration signals exhaustion of iterators in Python.

We'll cover the following...

Try it yourself

Try executing the code below to verify the result:

Python 3.8
nums = [4, 1, 3, 2]
rev = reversed(nums)
print(sorted(rev) == sorted(rev))

Explanation

The built-in reversed function returns an iterator.

Python’s ...