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

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
  • 62,419
  • 16
  • 94
  • 130
Mark Longair
  • 446,582
  • 72
  • 411
  • 327
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
  • 92,761
  • 29
  • 141
  • 204
Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
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
  • 28,112
  • 9
  • 59
  • 94
0

Try like this

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

saigopi.me
  • 14,011
  • 2
  • 83
  • 54