Puzzle 8 sorted? reversed?

Python Brain Teasers — by Miki Tebeka (17 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 User! Identify Yourself | TOC | A Simple Math 👉

sorted.py

​ 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.

images/hline.png

This code will print: False

images/hline.png

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…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.