[Python-ideas] Shuffled

Chris Angelico rosuav at gmail.com
Mon Sep 5 21:22:45 EDT 2016


On Tue, Sep 6, 2016 at 11:03 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, Sep 06, 2016 at 02:50:02AM +0200, Arek Bulski wrote:
>
>> We should add shuffled() analog to sorted. Also shuffle() should return
>> self so mutating methods could be chained.
>
> from random import shuffle
> shuffle(mylist)
>
> Why is that so important that it needs to be a built-in? In 15+ years of
> using Python, I've probably used shuffle() three or four times.

What you have isn't quite parallel to shuffled(). It'd need to be more like:

mylist = mylist[:]
shuffle(mylist)

to leave the original list untouched. Might make a nice utility
function for someone's personal tool collection, if they're doing this
a lot:

def shuffled(stuff):
    lst = list(stuff)
    random.shuffle(lst)
    return lst

Doesn't need - or want - to be a built-in, partly because shuffling
depends on an RNG, which you might want to swap out. At best, it would
be a method on the random.Random class... but that's not needed
either.

ChrisA


More information about the Python-ideas mailing list