Cannot get random.shuffle result form in python

I have never had this problem before, but when I try to shuffle the list, I get a "No" return

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

The print statement returns β€œNone,” and I don’t know why, I was looking for an answer to this problem, but there seems to be something. I hope I'm not mistaken.

+4
source share
4 answers

The random.shuffle function sorts the list in place, and to avoid confusion at this point, it does not return the shuffled list. Try simply:

  random.shuffle(c) print(c) 

This is a good API design, I think it means that if you don’t understand what random.shuffle doing, then you will immediately get the obvious problem, and not the more subtle error, which is difficult to track later on ...

+10
source

Remember that random.shuffle() moves into place. Therefore, it updates the object named "c". But then you reinstall "c" with None , the output of the function and the list is lost.

+3
source

From doc :

Shuffle the sequence x into place.

So,

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

works as expected.

+1
source

try it

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

0
source

Source: https://habr.com/ru/post/1342496/


All Articles