Is there some deeper meaning why Python's sorted
is documented as taking an iterable (which may be infinite) instead of a collection (which is sized)?
For example, this will run forever:
# DO NOT RUN
import itertools
for item in sorted(itertools.count()):
print(item)
I get that they'd want to allow sorted
to work on a collection's iterable object instead of the collection itself, but isn't there a fundamental difference (perhaps to be reflected in collections.abc
) between iterables that are guaranteed to raise a StopIteration
and iterables that may be infinite?
It is documented as such because it does not make use of __len__
for working, although you are right in that it should ask for a finite Iterable
for being meaningful. Note that an Iterable
can be finite and yet not support __len__
, contrarily to Collection
. Python does not make an explicit distinction between finite and indefinite Iterable
s.
Consider the following toy example:
x = iter(range(10, 0, -1))
len(x)
# TypeError: object of type 'range_iterator' has no len()
# BUT
y = sorted(x)
print(y)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With