4

I have never had this problem before but when i try and shuffle a list i get a return of 'None'

import random
c=[1,4,67,3]
c=random.shuffle(c)
print c

The print statement returns 'None' and i dont know why, I have looked around for an answer to this problem but there doesent seem to be anything. I hope i am not making an obvious mistake.

Koreus7
  • 43
  • 3
  • Possible duplicate of [Why does random.shuffle return None?](https://stackoverflow.com/questions/17649875/why-does-random-shuffle-return-none) – Martin Thoma Jul 23 '17 at 07:30

4 Answers4

10

The random.shuffle function sorts the list in-place, and to avoid causing confusion on that point, it doesn't return the shuffled list. Try just:

 random.shuffle(c)
 print(c)

This is a nice bit of API design, I think - it means that if you misunderstand what random.shuffle is doing, then you'll get a obvious problem immediately, rather than a more subtle bug that's difficult to track down later on...

PaulMcG
  • 59,676
  • 15
  • 85
  • 126
Mark Longair
  • 415,589
  • 70
  • 403
  • 320
3

Remember that random.shuffle() shuffles in-place. So it updates the object named “c”. But then you rebind “c” with None, the output of the function, and the list gets lost.

tzot
  • 87,612
  • 28
  • 135
  • 198
Morten Kristensen
  • 7,267
  • 4
  • 30
  • 51
1

From the doc :

Shuffle the sequence x in place.

So

import random
c=[1,4,67,3]
random.shuffle(c)
print c

works as expected.

khachik
  • 27,152
  • 7
  • 54
  • 92
0

Try like this

import random c=[1,4,67,3] random.shuffle(c) print c

saigopi.me
  • 11,721
  • 2
  • 72
  • 50