Paolo Dragone
Paolo Dragone

Reputation: 919

Python set sorted, Why so fast?

Why is Python built-in sorted on a set is so fast?

I mean, incredibly fast, I used it with a set of 80000 entries and it takes very very short time (0.0 is the output of the time.clock() difference). Is that some kind of optimization?

Are the records already sorted inside the set?

And, by the way, how is sorted for set implemented? Can you give me the code?

Upvotes: 1

Views: 953

Answers (1)

user4815162342
user4815162342

Reputation: 155046

There is no special magic: the sorting is implemented in C, efficiently. time.clock is not the ideal way to benchmark Python code, since the resolution of its output can be quite low on some platforms. For best results, use the timeit module to measure elapsed time.

There is also no special algorithm to sort sets. The sorted built-in, when called on a set (or anything else, for that matter) does the equivalent of:

def sorted(iterable):
    templist = list(iterable)
    templist.sort()
    return templist

So, the real magic is in the list.sort method. (The implementation is explained in some detail in the adjacent file.)

Upvotes: 3

Related Questions