How to pop random item from a list?

F

flamesrock

Hi,

It's been a while since I've played with python.

My question is... whats the best way to pop a random item from a list??

-Thanks
 
M

marduk

Hi,

It's been a while since I've played with python.

My question is... whats the best way to pop a random item from a list??

import random
# ...

item = mylist.pop(random.randint(0,len(mylist)))
 
B

Ben Cartwright

flamesrock said:
whats the best way to pop a random item from a list??

import random
def popchoice(seq):
# raises IndexError if seq is empty
return seq.pop(random.randrange(len(seq)))

--Ben
 
P

Peter Otten

marduk said:
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.

Peter
 
A

Andrew Gwozdziewycz

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,289
Messages
2,571,448
Members
48,126
Latest member
ToneyChun2

Latest Threads

Top