Panchi
Panchi

Reputation: 551

shuffle a python array WITH replacement

What is the easiest way to shuffle a python array or list WITH replacement??

I know about random.shuffle() but it does the reshuffling WITHOUT replacement.

Upvotes: 2

Views: 1360

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You are looking for random.choice() calls in a list comprehension:

[random.choice(lst) for _ in range(len(lst))]

This produces a list of the same length as the input list, but the values can repeat.

Demo:

>>> import random
>>> lst = [1,2,4,5,3]
>>> [random.choice(lst) for _ in range(len(lst))]
[3, 5, 1, 4, 1]

Upvotes: 4

Related Questions