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?

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
  • 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 08 '17 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 08 '17 at 14:53
  • 1
    Possible duplicate of [Why does random.shuffle return None?](http://stackoverflow.com/questions/17649875/why-does-random-shuffle-return-none) – Chris_Rands Mar 08 '17 at 15:01

2 Answers2

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']
vallentin
  • 23,478
  • 6
  • 59
  • 81
  • 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 08 '17 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 09 '19 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 09 '19 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'.

fivestarx
  • 21
  • 1