Search code examples
pythonalphabetical

Create alphabetically ascending list


I want to create alphabetically ascending names like the column names in excel. That is I want to have smth. like a,b,c,...,z,aa,ab,...az,...zz,aaa,aab,....

I have tried:

for i in range(1000):
    mod = int(i%26)
    div = int(i/26)
    print(string.ascii_lowercase[div]+string.ascii_lowercase[mod])

Which works until zz but than fails because it runs out of index

aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
.
.
.
zz

IndexError


Solution

  • You could make use of itertools.product():

    from itertools import product
    from string import ascii_lowercase
    
    for i in range(1, 4):
        for x in product(ascii_lowercase, repeat=i):
            print(''.join(x))
    

    First, you want all letters, then all pairs, then all triplets, etc. This is why we first need to iterate through all the string lengths you want (for i in range(...)).

    Then, we need all possible associations with the i letters, so we can use product(ascii_lowercase) which is equivalent to a nested for loop repeated i times.

    This will generate the tuples of size i required, finally just join() them to obtain a string.

    To continuously generate names without limit, replace the for loop with while:

    def generate():
        i = 0
        while True:
            i += 1
            for x in product(ascii_lowercase, repeat=i):
                yield ''.join(x)
    
    generator = generate()
    next(generator)  # 'a'
    next(generator)  # 'b'
    ...