Python Language Random and sequences: shuffle, choice and sample

Download Python Language for free

Example

import random

shuffle()

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)

print(laughs)
# Out: ["He", "Hi", "Ho"]  # Output may vary!

choice()

Takes a random element from an arbitary sequence:

print(random.choice(laughs))
# Out: He                  # Output may vary!

sample()

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