Python: How To Generate a List Of Letters In The Alphabet

In today’s post I show you how to use three python built in functions to populate a list with letters of the alphabet. To achieve our goal we will the chr() and ord() built-in functions. I will also explain how to use the map() function to make your code look cleaner.

To the code:

# First we need to figure out the ASCII code of the alphabet letters
# using the ord() function. 

>>> ord('a')
97
>>> ord('z')
122

# Get ASCII code for uppercase alphabet letters
>>> ord('A')
65
>>> ord('Z')
90

# Create alphabet list of lowercase letters
alphabet = []
for letter in range(97,123):
    alphabet.append(chr(letter))

>>> alphabet
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# Create alphabet list of uppercase letters
alphabet = []
for letter in range(65, 91):
    alphabet.append(chr(letter))

>>> alphabet
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']


Take a look at the ASCII Chart here, you will notice that the alphabet starts at ASCII code 65 and ends at 90. Lowercase alphabet letters start at 97 and end at 122. To create the list of letters, we call the chr() function for each number in the specified range. Each call to chr returns the corresponding alphabet letter.

To improve the readability of the code we use map(). Map takes a function and an iterable as arguments. map applies the function passed to it to every item of the iterable and returns a list.

# Use map to create lowercase alphabet
>>> alphabet = map(chr, range(97, 123))
>>> alphabet
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# Use map to create uppercase alphabet
>>> alphabet = map(chr, range(65, 91))
>>> alphabet
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

The End

That is all for now. If you enjoyed this post or found it helpful, please subscribe, share or follow me on Twitter.