Search code examples
pythonpython-3.xsetpython-itertools

How can I Iterate through all possible unique pairs using elements from a set?


I'd normally write:

for i in range(len(collection)):
    for j in range(i + 1, len(collection)):
        print(collection[i], collection[j])

That relies on the elements being ordered. How can it be done when using an unordered collection?


Solution

  • You can use itertools.combinations:

    import itertools as it
    
    result = it.combinations(collection, 2)