On Wed, Nov 30, 2016 at 11:52 AM, Chris Kaynor <ckay...@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
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to