Search code examples
pythoncombinationspython-itertoolsparentheses

Remove parenthesis from itertools.combinations list


I want to make a list of all possible combinations in a range of numbers, and print them line by line without surrounding parentheses. Here is the code I've built so far.

import itertools

x = range(1,4
y = list(itertools.combinations(x,2))

combos = []
for i in range(len(y)):
       combos.append(y[i])
       print(combos[i])

The output is

(1,2)
(1,3)
(2,3)

I need it to print the output without surrounding parentheses. I've looked high and low for a solution, but so far I can't find anything. Any help would be much appreciated.


Solution

  • Here's a simple way to do this.

    import itertools
    
    x = range(1,4)
    y = list(itertools.combinations(x,2))
    
    for pair in y:
        print(*pair)
    

    If you really want the separating commas, you could do this:

    import itertools
    
    x = range(1,4)
    y = list(itertools.combinations(x,2))
    
    for pair in y:
        print(f"{pair[0]},{pair[1]}")