11
votes

I was wondering about the time complexity of the shuffle function in the random Python library/module. Is it O(n) or is it less than that?

Is there a website that shows the time complexities of functions that belong to Python libraries?

1
For your second question - wiki.python.org/moin/TimeComplexity - Alex L
@Alex: considering the only library in that list is collections, not quite what OP is asking for, I think. - Wooble
@Wooble It's a wiki, so it may not be limited to just collections in the future. (Upon re-reading, it seems like this is for CPython, but at least an interesting reference. It may inspire someone to create an equivalent wiki page for random, and other libraries) - Alex L

1 Answers

19
votes

You cannot shuffle a list in a completely random fashion in less than O(n).

The implementation of random.shuffle() uses the Fisher-Yates shuffle algorithm, which is easily seen to be O(n).