Search code examples
pythonpython-itertools

Unique co-occurrence pairs with itertools.product()


I have a list of words, for example:

[man, walk, ball]

and I wish to produce their co-occurrences; i.e.:

[('man', 'walk'), ('man', 'ball'), ('walk', 'ball')]

I use the following code:

from itertools import product
my_list = [man, walk, ball]
list(product(my_list, my_list))

which gives me:

[('man', 'man'), ('man', 'walk'), ('man', 'ball'), ('walk', 'man'), ('walk', 'walk'), ('walk', 'ball'), ('ball', 'man'), ('ball', 'walk'), ('ball', 'ball')]

I wonder how to omit duplicate pairs?


Solution

  • Try itertools.combinations(iterable, r):

    >>> import itertools
    >>> list(itertools.combinations(['man', 'walk', 'ball'], 2))
    [('man', 'walk'), ('man', 'ball'), ('walk', 'ball')]