Monday, November 7, 2022

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

Issue

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)


Answered By - a_guest
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.