pythonlistrandomshufflein-place

what does 'in place' exactly mean in simple terms when people say "random.shufle shuffles the sequence 'in place' "?


I'm having trouble understanding what people mean when they say "random.shufle shuffles the sequence 'in-place'" when referring to why directly printing out random.shuffle returns the value 'None' instead of just the shuffled list itself.

Referring to the answers of this question in specific.

What does 'in place' exactly mean here? Please explain in newbie terms if possible, beginner here. Thank you.

talking about this bit of code

import random

b = [object(), object()]

print(random.shuffle(b))

which prints out: None

Another question like this exists on here but it doesn't explain is simple/beginner terms, more complex ones.


Solution

  • You are passing a list to the shuffle function. The list will be shuffled (pseudo-randomly rearranged). The function does not return anything (apart from implicit None). Thus your list will be modified.

    This could be demonstrated as follows:

    from random import shuffle
    
    my_list = [1, 2, 3, 4, 5]
    
    shuffle(my_list)
    
    print(my_list)
    

    An output could be:

    [1, 5, 3, 4, 2]
    

    Therefore you can see that the list itself has been modified - i.e., "in place"