+ 5

List of alphabet letters in Python

Hi. Two questions: 1) Is it possible to have/use list of letters (alphabet) in any shorter way then listed them as I usually see here in many codes: letters = ['a', 'b', 'c', ... 'y', 'z']? Something similar (or not) like range for numbers: range(1, 26) or in regex [a-z]. 2) If there is a shorter or simpler way why do you use a "traditional" list of alphabet letters so often?

10th Sep 2018, 6:41 AM
blackfish
blackfish - avatar
7 Answers
+ 7
#I wont say its faster or better, but here is another way. a=ord('a') alph=[chr(i) for i in range(a,a+26)]
10th Sep 2018, 7:09 AM
Louis
Louis - avatar
+ 7
Wow! And other string module data: ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' hexdigits = '0123456789abcdefABCDEF' octdigits = '01234567' printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' whitespace = ' \t\n\r\x0b\x0c'
10th Sep 2018, 8:04 AM
blackfish
blackfish - avatar
+ 4
I have found soething like that too: spam = list(map(chr, range(97, 123))) eggs = list(map(chr, range(ord('a'), ord('z')+1)))
10th Sep 2018, 7:58 AM
blackfish
blackfish - avatar
+ 3
Impatient... It took me a while longer to find the answer in the Internet. When importing string module we can use e.g.: import string eggs = list(string.ascii_lowercase) But the second question has been still waiting for the answer. Is it a "good practice" or just simpler or faster (for code) using it this or that way?
10th Sep 2018, 6:51 AM
blackfish
blackfish - avatar
+ 3
The second method is certainly more Pythonic. Even if one of them is faster, the margin should be negligible.
10th Sep 2018, 7:01 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Here is an easy way using comprehension: letters=[chr(x+97) for x in range(26)]
15th Nov 2019, 8:58 PM
Sirin Öngörur
Sirin Öngörur - avatar
0
>>> import string >>> list(string.ascii_lowercase) ['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'] If you want more details, you can check here: https://stackoverflow.com/questions/16060899/alphabet-range-in-JUMP_LINK__&&__python__&&__JUMP_LINK
22nd Jun 2020, 4:28 PM
Miguel Zabala
Miguel Zabala - avatar