dimanche 26 avril 2020

Shuffling part of a list in-place

I have a list and I want to shuffle a portion of it in-place.

I am aware of random.shuffle() and that working in-place, but if I slice it, it shuffles the sliced-copy of the original input, leaving the original list untouched:

import random


l = list(range(20))
print(l)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

random.shuffle(l[:10])  # I wish it was shuffling the first half
print(l)  # but does nothing to `l`
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

What options do I have?




Aucun commentaire:

Enregistrer un commentaire