@rhettinger I would use it often. My frequent use case would be for solution in shuffled(solutions):
, which I do for benchmarking competing solutions. I dislike doing shuffle(solutions)
beforehand, mostly because I really do mean shuffled iteration, and for solution in shuffled(solutions):
expresses that much more clearly.
Another case from a few days ago:
tmp = parts[1::2]
shuffle(tmp)
parts[1::2] = tmp
I’d much prefer:
parts[1::2] = shuffled(parts[1::2])
which reads much more nicely (like one operation), doesn’t leave that tmp
list lying around, and doesn’t push two other lines of code out of view.
Note I will never use sample
in such situations. Because I don’t want to sample. I want to shuffle. As I argued on GitHub, I don’t think sampling generally includes shuffling. I’d find it abusive/misleading to use random.sample
just because it happens to also shuffle (and I don’t like that the shuffle
doc suggests doing that). Also, yes, I would loathe having to explicitly write the length. Which in the above case with len(parts[1::2])
would even make another copy of the slice.
Btw, I see that random.sample
doesn’t optimize this “all” case, so it’s slower and takes much more memory than creating a list and calling random.shuffle
on it would.
@Gouvernathor I wouldn’t necessarily call my comment a proposal… random.shuffled
has been proposed and rejected a few times already.