Generate any number of combination of letter | Python generate all 3 letter combinations

We can generated all possible combination of alphabets or number using python with only few lines of code. We can use these combination to give unique identity to any one. Lets do it.

We will use these two standard library of python

import string
from itertools import combinations

We will get all alphabets using string library to generate combination

letters = list(string.ascii_lowercase)

Now we will create a function which we can used to generate any length combination

def generateCombination(lots, length):
    combilist = []
    for comb in combinations(lots, length):
        combilist.append(''.join(comb))
    return combilist

Now final code is

import string
from itertools import combinations
letters = list(string.ascii_lowercase)

def generateCombination(lots, length):
    combilist = []
    for comb in combinations(lots, length):
        combilist.append(''.join(comb))
    return combilist
# function calling
print(generateCombination(letters, 3))

You can use number instead of letter or you can use combination of both to generate combination like letters.extend(string.digits) now letters list combination numbers as well

Leave a Reply