Python - Ways to initialize list with alphabets

PythonServer Side ProgrammingProgramming

While working with lists, sometimes we wish to initialize the list with the English alphabets a-z. This is an essential utility in certain applications.

Example

 Live Demo

# using naive method
# initializing empty list
test_list = []
# printing initial list
print ("Initial list : " + str(test_list))
# using naive method
# for filling alphabets
alpha = 'a'
for i in range(0, 26):
   test_list.append(alpha)
   alpha = chr(ord(alpha) + 1)
# printing resultant list
print ("List after insertion : " + str(test_list))
# using list comprehension
# initializing empty list
test_list = []
# printing initial list
print ("Initial list : " + str(test_list))
# using list comprehension
# for filling alphabets
test_list = [chr(x) for x in range(ord('a'), ord('z') + 1)]
# printing resultant list
print ("List after insertion : " + str(test_list))
# using map()
# initializing empty list
test_list = []
# printing initial list
print ("Initial list : " + str(test_list))
# using map()
# for filling alphabets
test_list = list(map(chr, range(97, 123)))
# printing resultant list
print ("List after insertion : " + str(test_list))
# using string
import string
# initializing empty list
test_list = []
# printing initial list
print ("Initial list : " + str(test_list))  
# using string
# for filling alphabets
test_list = list(string.ascii_lowercase)  
# printing resultant list
print ("List after insertion : " + str(test_list))

Output

Initial list : []
List after insertion : ['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']
Initial list : []
List after insertion : ['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']
Initial list : []
List after insertion : ['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']
Initial list : []
List after insertion : ['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']
raja
Published on 06-Aug-2020 17:50:24
Advertisements