Python Language Random and sequences: shuffle, choice and sample

Download Python Language for free


import random


You can use random.shuffle() to mix up/randomize the items in a mutable and indexable sequence. For example a list:

laughs = ["Hi", "Ho", "He"]

random.shuffle(laughs)     # Shuffles in-place! Don't do: laughs = random.shuffle(laughs)

# Out: ["He", "Hi", "Ho"]  # Output may vary!


Takes a random element from an arbitary sequence:

# Out: He                  # Output may vary!


Like choice it takes random elements from an arbitary sequence but you can specify how many:

#                   |--sequence--|--number--|
print(random.sample(    laughs   ,     1    ))  # Take one element
# Out: ['Ho']                    # Output may vary!

it will not take the same element twice:

print(random.sample(laughs, 3))  # Take 3 random element from the sequence.
# Out: ['Ho', 'He', 'Hi']        # Output may vary!

print(random.sample(laughs, 4))  # Take 4 random element from the 3-item sequence.

ValueError: Sample larger than population

Random Binary Decision