Shuffle a list using Fisher-Yates algorithm in Python
Advertisements
We have already discussed Fisher-Yates algorithm in detail, which is the perfect shuffling algorithm to exist.
from copy import deepcopy from random import randint def shuffle(lst): tmplist = deepcopy(lst) m = len(tmplist) while (m): m -= 1 i = randint(0, m) tmplist[m], tmplist[i] = tmplist[i], tmplist[m] return tmplist print(shuffle([1,2,3,4,5,6])) #[4, 6, 2, 5, 3, 1]