61 of 151 menu

The shuffle method of random module

The shuffle method of the random module shuffles the order of elements in a mutable sequence. Since a tuple is an immutable sequence and the elements in a set are unordered, it turns out that the method only works with a list. After executing the method, the original list is changed, and the method itself returns None. In the method parameter, we pass the list we need.

Syntax

import random random.shuffle(list)

Example

Let's shuffle the elements in the list:

lst = [1, 2, 3, 4, 5] random.shuffle(lst) print(lst)

Result of code execution:

[4, 3, 2, 1, 5]

Example

Now let's try to shuffle the elements of the tuple:

tpl = ('1', '2', '3', '4', '5') random.shuffle(tpl) print(tpl)

We will get the following error back:

TypeError: 'tuple' object does not support item assignment

Example

Let's also try to mix the elements of the set:

st = {'a', 'b', 'c', 'd'} random.shuffle(st) print(st)

After executing the code we will get the following error:

TypeError: 'set' object is not subscriptable

See also

  • method choice of module random,
    which returns a random element from a sequence
  • method random of module random,
    which returns a pseudo-random number
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline