The pythonic way to generate pairs
These are not really "combinations" in the sense of combinatorics, these are rather elements from the cartesian product of a
and b
. The function in the standard library to generate these pairs is itertools.product()
:
for i, j in itertools.product(a, b):
# whatever
As @Sven said, your code is attempting to get all ordered pairs of elements of the lists a
and b
. In this case itertools.product(a,b)
is what you want. If instead you actually want "combinations", which are all unordered pairs of distinct elements of the list a
, then you want itertools.combinations(a,2)
.
>>> for pair in itertools.combinations([1,2,3,4],2):
... print pair
...
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)