user2768466
user2768466

Reputation:

Get all possible combinations of characters in list

I have a list [".","_","<<",">>"]

What i need is to get all strings with length of 4 with all possible combinations where each character is one of the above list .

example : "._<<>>","__<<>>",".<<<<>>" ... etc

now i am doing it for length of 4 :

mylist = [".","_","<<",">>"]
for c1 in mylist:
    for c2 in mylist:
        for c3 in mylist:
            for c4 in mylist:
                print "".join([c1,c2,c3,c4])

but that looks ugly , and what if i need to scale it up to length of 10 or more ?

Upvotes: 1

Views: 310

Answers (2)

Alexander
Alexander

Reputation: 12795

You can use itertools.product for that purpose

n = 4
for symbols in itertools.product([".","_","<<",">>"], repeat=n):
    print "".join(symbols)

one-liner :

print "\n".join(["".join(s) for s in itertools.product([".","_","<<",">>"], repeat=n)])

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1124538

Use itertools.product() to generate the combinations for you, without nested loops:

from itertools import product

mylist = [".", "_", "<<", ">>"]
length = 4
for chars in product(mylist, repeat=length):
    print ''.join(chars)

Simply adjust the length variable to get longer combinations.

Upvotes: 3

Related Questions