Using Python, I’d like to compare every possible pair in a list.
Suppose I have
my_list = [1,2,3,4]
I’d like to do an operation (let’s call it foo) on every combination of 2 elements from the list.
The final result should be the same as
foo(1,1)
foo(1,2)
...
foo(4,3)
foo(4,4)
My first thought was to iterate twice through the list manually, but that doesn’t seem very pythonic.
Check out
product()in theitertoolsmodule. It does exactly what you describe.This is equivalent to:
Edit: There are two very similar functions as well,
permutations()andcombinations(). To illustrate how they differ:product()generates every possible pairing of elements, including all duplicates:permutations()generates all unique orderings of each unique pair of elements, eliminating thex,xduplicates:Finally,
combinations()only generates each unique pair of elements, in lexicographic order:All three of these functions were introduced in Python 2.6.