fastest method to choose a random element

"Martin v. Löwis" martin at v.loewis.de
Sat Jan 5 12:12:48 EST 2008


> Any other ideas? 

How about this:

def random_pick(list, property):
    L = len(list)
    pos = start = random.randrange(L)
    while 1:
        x = list[pos]
        if property(x): return x
        pos = (pos + 1) % L
        if pos == start:
           raise ValueError, "no such item"

Regards,
Martin





More information about the Python-list mailing list