Random.sample was changed to work with sets and other non- indexable iterables, but random.choice still requires that its argument be a full sequence. Should that possibly be changed, so that for lists random.choice uses the current implementation, but for other iterables that random.sample supports, it could return random.sample(iterable, 1)[0]?
Logged In: YES user_id=80475 I would not like to see that accommodation extended to random.choice(). In random.sample(), it was done to eliminate a surprising assymetry between the two internal algorithms. Because one used list(population) and the other used population.__getitem__(), the first would work with any iterable and the second demanded random access. So, for certain values of n, dictionaries would work find and for other values they would fail. This consideration does not apply to random.choice(). I think most people have a mental model of how it works and would be surprised to have an iterable input fully manitested in memory. Though, I do grant that it is also surprising that it does not work with sets. C'est le vie.
Logged In: YES user_id=99508 An iterable input does not have to be fully manifested in memory for random.choice to work. See the implementation at <http://www.pastebin.de/pastebin.py? id=594>. Is this to say that random.sample entirely manifests large iterables in memory? I would say that this would be just as unexpected as random.choice doing so. If it's not the case, then why can't random.choice do what it does now for proper sequences, but just dispatch to random.sample(iterable, 1)[0] in all other cases?
Logged In: YES user_id=31435 I agree with Raymond on this -- making random.choice() an O (n) function in some cases would make it an attractive nuisance. In the absence of an efficient implementation, it's regrettable that random.sample() decided to cater to sets. Doing more damage of the same kind would primarily be doing more damage.