Shuffling a list of objects
The random
module in Python provides a function called shuffle()
which can be used to shuffle the elements of a list. Here is an example:
This will randomly shuffle the elements of the list my_list
and print the new order of elements.
Alternatively, you can use the random.sample()
method to return a shuffled list of elements from the original list.
import random
my_list = [1, 2, 3, 4, 5]
shuffled_list = random.sample(my_list, k=len(my_list))
print(shuffled_list)
This will return a shuffled list of elements from the original list, but this will not change the original list
Note that if you are working with large lists, shuffling them in place (i.e., using random.shuffle()
) will be more efficient than creating a new list (i.e., using random.sample()
).