How to pop random item from a list?

Andrew Gwozdziewycz apgwoz at gmail.com
Sat Mar 11 13:37:07 EST 2006


On Mar 11, 2006, at 11:21 AM, Peter Otten wrote:

> Am Freitag, 10. März 2006 19:38 schrieben Sie:
>
>>>> item = mylist.pop(random.randint(0,len(mylist)))
>>>
>>> This is broken because randint(a, b) may return b.
>>> I prefer randrange(len(mylist)) over randint(0, len(mylist)-1) as  
>>> a fix.
>>
>> This brings up an interesting proposal.
>> random.choice(seq) brings back a random element from a list, why not
>> add an optional second argument which is a flag to pop the element
>> instead of choosing?
>>
>> ie.
>>
>>>>> import random
>>>>> def choice(seq, pop=False):
>>
>> ...     if not pop:
>> ...         return seq[random.randrange(len(seq))]
>> ...     else:
>> ...         return seq.pop(random.randrange(len(seq)))
>> ...
>>
>>>>> x = [1, 2, 3]
>>>>> choice(x)
>>
>> 1
>>
>>>>> x
>>
>> [1, 2, 3]
>>
>>>>> choice(x, True)
>>
>> 1
>>
>>>>> x
>>
>> [2, 3]
>
> [The main reason I am answering your mail is because you may have  
> intended to
> post on c.l.py]
>
> Regarding your enhancement, I don't see any use cases that aren't  
> handled by
> random.sample() already.
>
> Regards,
> Peter

I can see a use case. Think of a bag datastructure. You push things  
into some container
and pop them out randomly. If random.choice was capable of 'pop' it  
would be
implemented implicitly.

random.sample, select elements from a list, but the original list  
remains intact. This would
not be the desired 'bag' behavior.


---
Andrew Gwozdziewycz
apgwoz at gmail.com
http://ihadagreatview.org
http://and.rovir.us





More information about the Python-list mailing list