How to shuffle randomly elements of a list in python ?

Published: August 06, 2021

Tags: Python; List; Random; Sample; shuffle;

DMCA.com Protection Status

Examples of how to shuffle randomly elements of a list in python:

Create a list in python

Lets first create a list:

mylist = ['a','b','c','d','e','f']

Shuffle list elements

To shuffle list elements, a solution is to use shuffle from the module random

random.shuffle(mylist)

print(mylist)

returns for example

['c', 'a', 'f', 'e', 'd', 'b']

Create a sample from a list

Another solution is to create a sample

mylist = ['a','b','c','d','e','f']

sample = random.sample(mylist,2)

sample

returns for example

['a', 'b']

If the sample has the same size that the list, it will shuffle all list elements:

sample = random.sample(mylist,len(mylist))

sample

returns for example

['e', 'c', 'b', 'f', 'd', 'a']

References