choosing random numbers with weights/probability?

Michael Hudson mwh21 at
Mon Jun 21 19:17:54 EDT 1999

kevinsl <kevinsl at> writes:

> I've been using the whrandom.choice routine and it's very
> useful. But is there any way to add weights or
> probabilities of being chosen to the items in the list?
> example:
> list=['one','two','three']
> item=whrandom.choice(list)
> Is there any way to say that 'one' and 'two' have a 25%
> chance of being chosen, and 'three' has a 50% chance?

One very obvious, not very extensible, way:


(NB: list is a builtin; using list as a variable name can lead to

A not very efficient but more general method:

def weighted_choice(choices):
    tot = 0
    for w,v in choices:
        tot = tot + w
    d = random.random()*tot
    tot = 0
    for w,v in choices:
        tot = tot + w
        if tot > d:
            return v


seems to work. Haven't tested it much, so please don't rely on it...


> I'm hoping there's already a module to do this... or else
> I'll be writing my own..
> thanks,
> Kevin

More information about the Python-list mailing list