[Python-ideas] Shuffled

Chris Kaynor ckaynor at zindagigames.com
Tue Sep 6 20:49:38 EDT 2016


On Tue, Sep 6, 2016 at 3:04 PM, Tim Peters <tim.peters at gmail.com> wrote:

> 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.
>

I'll weigh in and say that I've had a few cases where I've wanted a
shuffled function, but not many. The vast majority are interactive uses,
where I want to get a sampling of data, and in those cases I'm normally
just printing the output (often, by letting the REPL handle it).

I'm fairly sure I've never wanted a shuffled in the actual code, and
shuffle is almost always what I want (or just pulling items at random).

Probably the most common case is to produce a list of random numbers in a
(small) range. The current code looks roughly like:

import random
items = list(range(10))
random.shuffle(items)
items # this is interactive, so this prints it for me

As this does not come up often, I almost invariably write the following
first:
import random
random.shuffle(range(10))

Then get no output and write the first form. It is not a major difference,
and only comes up maybe a few times a year at most for me.

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160906/112b46a2/attachment.html>


More information about the Python-ideas mailing list