4

Is there a way in python to perform the same function as enumerate() but with letters instead?

For example

x = ['block', 'cheese']

for i, word in enumerate(x):
    print((i, word))

would produce

(1, 'block')
(2, 'cheese')

Is there a straightforward way to produce this?

('A', 'block')
('B', 'cheese')
Adam_G
  • 7,337
  • 20
  • 86
  • 148

3 Answers3

9

For up to 26 elements you can do:

import string

x = ['block', 'cheese']

for i, word in zip(string.ascii_uppercase, x):
    print((i, word))

Output

('A', 'block')
('B', 'cheese')
DarrylG
  • 16,732
  • 2
  • 17
  • 23
3

No it's not possible.

But maybe string.ascii_lowercase could help you

import string
string.ascii_lowercase
>>>>> 'abcdefghijklmnopqrstuvwxyz'
string.ascii_lowercase[0]
>>>>> a
AlexisG
  • 2,476
  • 3
  • 11
  • 25
1

You could relatively easy mimic Excel's behaviour with a generator:

def mimic_excel():
    for i in range(0, 26):
        yield chr(i + 65)

    i, j = [0, 0]

    for j in range(0, 26):
        for i in range(0, 26):
            yield "{}{}".format(chr(j + 65), chr(i + 65))


for letter in mimic_excel():
    print(letter)

This yields

A
B
C
...
ZX
ZY
ZZ
Jan
  • 42,290
  • 8
  • 54
  • 79