How to randomly sample letters in Python

In this tutorial, we will learn how to randomly sample from letters or alphabets. Python’s random module has number of functions to generate random numbers from different distribution. We will first randomly sample single letter using random module’s choice() function and then randomly sample multiple letters using random module’s choices() function.

Let us first load the modules needed to randomly sample letter.

import random
import string

We imported string module in Python as it has letters/alphabets readily available. string module’s ascii_letters has the alphabets/letters. string.ascii_letters has both lower case and upper case letters as a one long string. The first 26 letters in the string are lowercase letters and the next 26 letters are upper case letters in order.

string.ascii_letters

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

To randomly select a letter, we give the alphabet string as argument to random.choice() function. In the example below we have randomly sampled the letter “i”.

random.choice(string.ascii_letters)

'i'

By using the statement again, we have randomly sample the upper case C.

random.choice(string.ascii_letters)

'C'

Sampling multiple letters with replacement using random.choices()

If we are interested in randomly sampling multiple letters, we need to use “random.choices()” function.
Python’s random.choices() function randomly samples from the input with replacement and returns a list. It also takes in the number of elements to sample. The argument k specifies the number to be sampled randomly. In the example below, we are sampling 6 letters from ascii_letters with replacement.

random.choices(string.ascii_letters, k=6) 

['E', 'A', 'l', 'p', 'g', 'B']

If we apply the statement again, we get another random sampling of alphabets.

random.choices(string.ascii_letters, k=6) 

['o', 'b', 'Z', 'G', 'w', 'n']

Often we would like to reproduce the results from random sampling. To reproduce the same random sampling, we need to set the seed using random.seed() function. In the example below, we set the seed and verify if we get the same random sampling of letters. Also we sample from the first two letters in ascii_letters.

random.seed(2022)
random.choices(string.ascii_letters[0:2],k=6) 

['b', 'a', 'a', 'a', 'b', 'b']

We can confirm that we get the same random sampling by using the same seed again with the same code to sample.

random.seed(2022)
random.choices(string.ascii_letters[0:2],k=6) 

['b', 'a', 'a', 'a', 'b', 'b']