Search code examples
pythonpython-itertools

Unordered Pairs (pair sets) in Python from a list


I have a list of items

 alist = ['dog', 'cat', 'fish']

I want to return all unique unordered pairs, so in this case:

 (dog,cat)(dog,fish)(fish,cat)

itertools.combinations does not take into account the unordered condition, so it is not quite what I need.


Solution

  • Where is your problem with itertools?

    import itertools
    
    alist = ['dog', 'cat', 'fish']
    for result in itertools.combinations(alist, 2):
        print result
    

    output:

    ('dog', 'cat')
    ('dog', 'fish')
    ('cat', 'fish')