Are there any alternatives for the python module "random's shuffle function" in micropython?

Viewed 41

I am currently learning micropython. I know that in python, you can use the “random” module to shuffle a list.
Furthermore, I was wondering if there's any similar function for that in micropython as well, because in the “urandom” module, that function does not exist.

Any help is appreciated!

1 Answers

micropython can be compiled to have a randrange method available, this can be used to implement the Fisher–Yates shuffle. This is a relatively efficient in-place shuffle and can be expressed as:

from random import randrange

def shuffle(array):
    "Fisher–Yates shuffle"
    for i in range(len(array)-1, 0, -1):
        j = randrange(i+1)
        array[i], array[j] = array[j], array[i]
Related