Puzzle 8 sorted? reversed?
Python Brain Teasers — by Miki Tebeka (17 / 40)
👈 User! Identify Yourself | TOC | A Simple Math 👉
nums = [4, 1, 3, 2]
rev = reversed(nums)
print(sorted(rev) == sorted(rev))
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print: False
The built-in reversed function returns an iterator.
Python’s iterators can do two things:
- Return the next item (by using a for loop or calling the built-in next function)
- Signal there are no more items by raising StopIteration (we say the iterator is exhausted)
The first call to sorted(rev) consumes everything from the iterator. When you call sorted(rev) the second time, the iterator will immediately raise StopIteration and sorted will assume an empty iterator.
The result of the first sorted(rev) is [1, 2, 3, 4], and the result of the second sorted(rev) is [] (the empty…