Andrew
Andrew

Reputation: 367

Python, For loops depending on int

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.

Upvotes: 0

Views: 88

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

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)

Upvotes: 5

Related Questions