Shuffle a List with Random
random
is a Python module that implements pseudo-random number generators. random.shuffle
can shuffle a list in-place.
random.shuffle(x[, random]): Shuffle the sequence x in place.
The optional argument random is a 0-argument function returning
a random float in [0.0, 1.0); by default, this is the function random().
Let’s run a simple usage example. From the output we can see the list is modified after shuffling, this is called in-place
strategy:
import random
numbers = [71, 1, 21, 22, 35, 41, 49, 56, 63, 70]
print ("Original: ", numbers)
> ('Original: ', [71, 1, 21, 22, 35, 41, 49, 56, 63, 70])
random.shuffle(numbers) #shuffle method
print ("Shuffled: ", numbers)
> ('Shuffled: ', [49, 22, 63, 70, 56, 21, 1, 71, 41, 35])
We can also use random.shuffle()
to shuffle a list with strings.
a = ["hello", "coder", "cat"]
random.shuffle(a)
print(a)
> ['coder', 'hello', 'cat']
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 not-in-place
strategy:
import random
numbers = [71, 1, 21, 22, 35, 41, 49, 56, 63, 70]
new_numbers = random.sample(numbers, len(numbers))
print ("new_numbers: ", new_numbers)
> ('new_numbers: ', [56, 35, 49, 41, 71, 70, 22, 63, 1, 21])
Implement it by yourself
Challenge:
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:
from copy import deepcopy
from random import randint
def shuffle(lst):
tmp = deepcopy(lst)
m = len(tmp)
while(m):
m -= 1
i = randint(0, m)
tmp[m], tmp[i] = tmp[i], tmp[m]
return tmp
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
The post How to Shuffle a List in Python appeared first on CodersCat.
Top comments (0)