Shuffle a List with Random
random is a Python module that implements pseudo-random number generators.
random.shuffle can shuffle a list in-place.
Let’s run a simple usage example. From the output we can see the list is modified after shuffling, this is called
We can also use
random.shuffle() to shuffle a list with strings.
Shuffle a list with not-in-place
If we don’t want to modify the original list, we can use another function called
random.sample, it will return a new list and keep the original list un-touched.
This is called
Implement it by yourself
Implement a Python function which will shuffle a list, return a new list.
If this is an interview question, can you finish it bug-free in 15 minutes?
Have a try now :)
A simple algorithm for shuffling array or list is Fisher-Yates:
Join my Email List for more helpful insights, It's Free!😋