Practice Question: Iterator Exhaustion
What is the output of the following code snippet?
nums = [4, 1, 3, 2]
rev = reversed(nums)
print(sorted(rev) == sorted(rev))Answer
The output is:
Falsereversed(nums) returns an iterator, and iterators can only be consumed once.
The first
sorted(rev)consumes the iterator and returns[1, 2, 3, 4].The second
sorted(rev)receives an already-exhausted iterator (no next; StopIteration) and returns[].