Generating a random subsequence

Skip Montanaro skip at pobox.com
Mon Jan 7 11:14:32 EST 2002


    Tom> I needed to get a random subset of a list, and I was surprised that
    Tom> random didn't support it directly.

    import random
    def randomSubseq(seq, length):
        newseq = list(seq)
        random.shuffle(newseq)
        return newseq[:length]

I don't really like fiddling with the different sequence types in this
function.  I'd prefer to simply return the list and have the caller know how
to convert it back from a list if need be.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list