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?
Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.
shuffle() function in Python. The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list).
The shuffle() method randomizes the items of a list in place.
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']
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With