Search⌘ K
AI Features

All Sorted?

Explore how Python's sorted method returns a list while reversed returns an iterator. Understand the implications for comparing lists and tuples, and why sorted consumes iterators during repeated calls. This lesson helps you avoid unexpected behavior when working with sorted and reversed in Python.

We'll cover the following...

Is everything in your life sorted out? Probably not.

C++
x = 7, 8, 9
print(sorted(x) == x)
print(sorted(x) == sorted(x))
y = reversed(x)
print(sorted(y) == sorted(y))

Explanation

  • The sorted method always returns a list, and comparing lists and tuples
...