[Python-ideas] Allow random.choice, random.sample to work on iterators

Chris Kaynor ckaynor at zindagigames.com
Wed Nov 30 14:57:46 EST 2016


On Wed, Nov 30, 2016 at 11:52 AM, Chris Kaynor <ckaynor at zindagigames.com> wrote:
> There are also issues with how it should behave on iterables that
> cannot be re-iterated (eg, random.choice will consume the iterator,
> and could only be called once safely).

I meant to include a sample in my previous e-mail:

Consider that this code will not produce the "correct" results (for a
reasonable definition of correct):

a = (i for i in range(100)) # Pretend this does something more
interesting, and isn't a trivial generator - maybe a file object
reading by line.
randomEntries = [random.choice(a) for i in range(10)] # May not be
quite as obvious, such as the choices could be chosen in a more
complex loop.

randomEntries may not contain 10 items (or the generation may error
due to having insufficent items, depending on implementation), it will
not contain duplicates, and will be sorted. This occurs because the
first call to random.choice will consume elements from a until it
picks one. The next call then consumes from there until it picks one,
and so forth.

Chris


More information about the Python-ideas mailing list