Horai Nuri
Horai Nuri

Reputation: 5578

How to shuffle the order in a list?

I would like to shuffle the order of the elements in a list.

from random import shuffle
words = ['red', 'adventure', 'cat', 'cat']
shuffled = shuffle(words)
print(shuffled) # expect new order for, example ['cat', 'red', 'adventure', 'cat']

As response I get None, why?

Upvotes: 19

Views: 43137

Answers (2)

fivestarx
fivestarx

Reputation: 21

random.shuffle() is a method that does not have a return value. So when you assign it to a identifier (a variable, like x) it returns 'none'.

Upvotes: 2

vallentin
vallentin

Reputation: 26167

It's because random.shuffle shuffles in place and doesn't return anything (thus why you get None).

import random

words = ['red', 'adventure', 'cat', 'cat']
random.shuffle(words)

print(words) # Possible Output: ['cat', 'cat', 'red', 'adventure']

Edit:

Given your edit, what you need to change is:

from random import shuffle

words = ['red', 'adventure', 'cat', 'cat']
newwords = words[:] # Copy words
shuffle(newwords) # Shuffle newwords

print(newwords) # Possible Output: ['cat', 'cat', 'red', 'adventure']

or

from random import sample

words = ['red', 'adventure', 'cat', 'cat']
newwords = sample(words, len(words)) # Copy and shuffle

print(newwords) # Possible Output: ['cat', 'cat', 'red', 'adventure']

Upvotes: 42

Related Questions