Sebastian Wozny
Sebastian Wozny

Reputation: 17506

Functionally shuffling a list

There are quite a few questions on stack overflow regarding the random.shuffle method of the random module.

Something that irks me about shuffle is that it shuffles in-place rather than returning a shuffled copy.

Note that shuffle works in place, and returns None.

Therefore expressions like

for index, (parent1, parent2) in enumerate(zip(sorted(population)[::2], shuffle(population)[1::2])):

don't work. Writing it with a side effect seems unnecessarily verbose:

other_half = population[1::2]
random.shuffle(other_half)
for index, (parent1, parent2) in enumerate(zip(sorted(population)[::2], other_half):

What's a pythonic way of functionally shuffling a list?

Upvotes: 2

Views: 92

Answers (2)

DeepSpace
DeepSpace

Reputation: 81664

A good alternative would be random.sample with k being the len of the list:

import random

li = [1, 2, 3, 4, 5]

for _ in range(4):  # showing we get a new, 'shuffled' list
    print(random.sample(li, len(li)))

# [5, 2, 3, 1, 4]
# [1, 5, 4, 3, 2]
# [4, 2, 5, 1, 3]
# [4, 2, 3, 5, 1]

Upvotes: 2

stx101
stx101

Reputation: 271

This looks like a duplicate of this question

The accepted answer was

shuffled = sorted(x, key=lambda k: random.random())

Upvotes: 2

Related Questions