0

I have some code which prints every possible letter combination for a word length of 3.

letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"    ,"u","v","w","x","y","z"]
for x in range(0,26):
    for y in range(0,26):
        for z in range(0,26):
            print(letters[x],letters[y],letters[z])

This code works fine but if I wanted to see every 4 letter word, then I would have to add another for loop and the same for 5 letters and so on.

I am wondering how I can have a certain number of for loops depending on user input.

Andrew
  • 357
  • 2
  • 6
  • 13

1 Answers1

5

You itertools.product with a *repeat=n* where n is how many loops:

from itertools import  product
for p in product(letters,repeat=3):
    print(p)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321