19

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?

3
  • 2
    "I tried with shuffle from random library but it gives me a None error." You need to show us what you actually did.
    – Denziloe
    Mar 8, 2017 at 14:52
  • 4
    None is not an error. random.shuffle() shuffles the list in place and returns None. Check the contents of words after shuffling.
    – glibdud
    Mar 8, 2017 at 14:53
  • 1
    Possible duplicate of Why does random.shuffle return None? Mar 8, 2017 at 15:01

2 Answers 2

42

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']
3
  • 2
    @Lindow You might have done it like words = random.shuffle(words) or print(random.shuffle(words)) which is why it would print None.
    – vallentin
    Mar 8, 2017 at 15:18
  • what do you mean by "shuffles in place and doesn't return anything"? How copying the list solved the problem? what is difference between a list and copy of the list?
    – Reihan_amn
    May 9, 2019 at 17:55
  • 1
    @Reihan_amn For instance sorted returns a new list and doesn't change the given list. Whereas shuffle changes the given list and doesn't return a new/copy.
    – vallentin
    May 9, 2019 at 17:58
2

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'.

1
  • Nice answer but perhaps edit to show how to print the correct list.
    – Tls Chris
    Sep 1, 2020 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.