[Python-ideas] Shuffled

Tim Peters tim.peters at gmail.com
Tue Sep 6 18:04:19 EDT 2016


[David Mertz <mertz at gnosis.cx>]
> This definitely feels like a case of "put it on PyPI."  Actually, maybe
> contribute to `boltons`, it feels like it might fit as a utility function
> there.

It's trivial to write such a function if it's truly needed - it would
be easier to write it from scratch than to remember which module it's
hiding in.  There's a "clever" 1-liner, but with no imagination at all
it's still dead obvious:

    def shuffled(xs):
        from random import shuffle
        xs = xs[:]
        shuffle(xs)
        return xs

`boltons` doesn't typically bother with screamingly obvious things.


> While I wouldn't mind being able to type `from random import shuffled`, I
> don't have a bit problem instead typing `from boltons import shuffled`, nor
> even `from arek_utils import shuffled`.

But would you _use_ it?  I'm still asking for use cases.

When, e.g., I'm randomizing permutations for testing, the last thing I want is:

    while whatever:
        result = function_of_xs(shuffled(xs))
        check result and complain if it's wrong

Why not?  Because no trace remains of _which_ permutation provoked the
failure when a failure occurs.  Instead code looks like this:

    while whatever:
        shuffle(xs)
        result = function_of_xs(xs)  # or xs[:] if the function mutates its arg
        check result and complain that `xs` specifically provoked a failure

Indeed, the only clear "use case" that makes sense I've been able to
think of is:

    xs = shuffled(xs)

But that's written more easily and efficiently today as

    shuffle(xs)

This is in stark contrast to sorted(), where clear use cases abound.
That didn't get in because it's hard to mimic (it's basically as easy
as shuffled()), but because it's exactly what's wanted in all kinds of
contexts in all kinds of code.


More information about the Python-ideas mailing list