How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)

Seb picture Seb · Mar 30, 2015 · Viewed 8.7k times · Source

I would like to make a alphabetical list for an application similar to an excel worksheet.

A user would input number of cells and I would like to generate list. For example a user needs 54 cells. Then I would generate

'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb'

I can generate the list from [ref]

 from string import ascii_lowercase
 L = list(ascii_lowercase) 

How do i stitch it together? A similar question for PHP has been asked here. Does some one have the python equivalent?

Answer

Kevin picture Kevin · Mar 30, 2015

Use itertools.product.

from string import ascii_lowercase
import itertools

def iter_all_strings():
    for size in itertools.count(1):
        for s in itertools.product(ascii_lowercase, repeat=size):
            yield "".join(s)

for s in iter_all_strings():
    print(s)
    if s == 'bb':
        break

Result:

a
b
c
d
e
...
y
z
aa
ab
ac
...
ay
az
ba
bb

This has the added benefit of going well beyond two-letter combinations. If you need a million strings, it will happily give you three and four and five letter strings.


Bonus style tip: if you don't like having an explicit break inside the bottom loop, you can use islice to make the loop terminate on its own:

for s in itertools.islice(iter_all_strings(), 54):
    print s