Skip to content

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]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.