Search code examples
pythonoptimizationcombinationscombinatoricspython-itertools

Python, combinations, permutations without repeat


Python. I have two lists, same length. The idea is to build paired data (for regression analysis). I figured out loops and it look like this.

a=(1,3,5,7)   #first list
b=(2,4,6,10)  #second list
w=zip(a,b)    #paired values from both lists

i=0
j=0
for each in w:
    x= w[i]
    for that in xrange(i,len(w)-1):
        i+=1
        print x, w[i]
    j+=1
    i=j

The output is as I was expected - first pair together with second, third.. so on, then second pair with the third, fourth.. and so on (skipping the combination between second pair and first pair, because it is kinda the same as combination of first and second pairs...)

(1, 2) (3, 4)
(1, 2) (5, 6)
(1, 2) (7, 10)
(3, 4) (5, 6)
(3, 4) (7, 10)
(5, 6) (7, 10) [..] and so on as I was expecting.

The question is - is there some other, shorter, optimized ways how to rewrite this code, maybe using itertools?


Solution

  • Yes: itertools.combinations

    print list(itertools.combinations(w, 2))
    

    You mention this in your question - I'm not sure why you wouldn't look in the docs before asking on StackOverflow.