2

I want to generate all strings from "aaa" down to "zzz". Currently, I'm doing this using 3 for loops, is there a more pythonic way of doing this?

key_options = []
for n1 in range(ord('a'), ord('z')+1):
    for n2 in range(ord('a'), ord('z')+1):
        for n3 in range(ord('a'), ord('z')+1):
             key_options.append(chr(n1) + chr(n2) + chr(n3))
0

3 Answers 3

5

Use itertools.product and a list comprehension:

>>> from itertools import product
>>> from string import ascii_lowercase
>>> [''.join(p) for p in product(ascii_lowercase, repeat=3)]
['aaa', 'aab', 'aac', 'aad', 'aae', ..., 'zzv', 'zzw', 'zzx', 'zzy', 'zzz']
Sign up to request clarification or add additional context in comments.

Comments

2

The itertools module is a much better way to do this sort of loop. The product function is what you’d use:

itertools.product(*iterables[, repeat])

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

The string can provide the ASCII lowercase letters without using a range:

string.ascii_lowercase

The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.

Thus, you have

from itertools import product
from string import string

key_options = [''.join(n) for n in product(ascii_lowercase, repeat=3)]

Comments

1
>>> letters = [chr(i) for i in range(ord('a'), ord('z')+1)]
>>> letters
['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']

import itertools
["".join(i) for i in itertools.product(letters,letters,letters)]

Output

['aaa', 'aab', 'aac', ... 'zzy', 'zzz']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.