python - What is the best way to generate all possible three letter strings? -


i generating possible 3 letters keywords e.g. aaa, aab, aac.... zzy, zzz below code:

alphabets = ['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']  keywords = [] alpha1 in alphabets:     alpha2 in alphabets:         alpha3 in alphabets:             keywords.append(alpha1+alpha2+alpha3) 

can functionality achieved in more sleek , efficient way?

keywords = itertools.product(alphabets, repeat = 3) 

see documentation itertools.product. if need list of strings, use

keywords = [''.join(i) in itertools.product(alphabets, repeat = 3)] 

alphabets doesn't need list, can string, example:

from itertools import product string import ascii_lowercase keywords = [''.join(i) in product(ascii_lowercase, repeat = 3)] 

will work if want lowercase ascii letters.


Comments