Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through the alphabet? [duplicate]

How can I iterate through the alphabet and have it continue past the letter Z? For example - a,b,c ... y,x,aa,ab,ac,ad

At the momenent this is my array

letters = [
           "a","b","c","d","e","f","g","h","i","k",
           "l","m","n","o","p","q","r","s","t","u",
           "v","w","x","y","z", "aa", "ab", "ac", "ad", "ae",
           "af", "ag", "ah", "ai", "aj", "ak", "al", "am", "an",
           "ao", "ap", "aq", "ar", "as", "at", "au", "av","aw", "ax", "ay",
           "az", "ba", "bb", "bc", "bd", "be", "bf", "bg", "bh", "bi",
           "bj", "bk", "bl", "bm", "bn", "bo", "bp", "bq", "br", "bs", "bt",
           "bu", "bv","bw", "bx", "by", "bz","ca","cb","cc","cd","ce",
           "cf","cg","ch","ci","cj","ck","cl","cm","cn","co","cp",
           "cq","cr","cs","ct","cu","cv","cw"]

but I want to make it created within a loop.

like image 248
slothinspace Avatar asked Sep 19 '25 12:09

slothinspace


2 Answers

You can try this:

import string

letters = list(string.ascii_lowercase)

letters.extend([i+b for i in letters for b in letters])

print letters

By using a double for loop, we iterate over the alphabet like we normally would, except we can put the iteration in list comprehension, to save space and be more pythonic.

like image 131
Ajax1234 Avatar answered Sep 22 '25 04:09

Ajax1234


since string.ascii_lowercase holds all of the lower-case letters, you can iterate through them in one loop (for 1-letter-string) or two (for 2-letters-string) and just add them to a list, like this:

import string
list = []
for c in string.ascii_lowercase: 
    list.append(c)

for c1 in string.ascii_lowercase:
    for c2 in string.ascii_lowercase:
        list.append(c1+c2)

print(list)
like image 21
CIsForCookies Avatar answered Sep 22 '25 03:09

CIsForCookies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!