Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sorted documented as taking an iterable instead of a collection?

Tags:

python

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?

like image 362
MikeRand Avatar asked Mar 03 '23 02:03

MikeRand


1 Answers

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

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]
like image 52
norok2 Avatar answered Mar 05 '23 16:03

norok2