When generating a random list, the random.shuffle() function is used. The following questions arise about the call of this function:
If a list is explicitly defined, such as li = [], the shuffle function It can produce the desired results;
But if list(range(n)) is used as the parameter of shuffle, None will be returned. As shown in the figure:
What's going on? They all belong to the list category
It is mentioned in the document that if an
is givenlist
对象, 则直接作用鱼list
objectBecause
random.shuffle()
会直接作用于list
本身,而不会返回任何值,所以你第一个语句的结果会是None.但是在random.shuffle(li)
的时候,你打印的是li
this list itself has been changed. If you write like thisThen it will return the same way
None
.所以想要得到list(range(20))
被shuffle
操作过后的值,需要先给它一个变量名,在被shuffle
You can access it only after the operation.