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

Terry Reedy tjreedy at udel.edu
Fri Dec 2 20:58:21 EST 2016


On 12/1/2016 3:19 AM, Sjoerd Job Postmus wrote:
> On Wed, Nov 30, 2016 at 02:32:54PM -0600, Nick Timkovich wrote:
>> a generator with known length that's not indexable (a rare beast?).

I don't believe a generator is ever indexable.

> Not as rare as you might think:
>
>>>> k = set(range(10))
>>>> len(k)
> 10
>>>> k[3]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   TypeError: 'set' object does not support indexing

It is also not a generator.  (It is an iterable.).  If an *arbitrary* 
choice (without replacement) from a set is sufficient, set.pop() works. 
Otherwise, make a list.  If we wanted selection selection from sets to 
be easy, without making a list, we should add a method that accesses the 
internal indexable array.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list