I'm attempting to iterate over pairs of combinations.
Although I have figured out a better way of doing this, from both a conceptual and pragmatic perspective, this was my first impulse, and I'm wondering why it didn't work.
gen = itertools.combinations(range(1, 6), 3)
for i in gen:
gen, gencopy = itertools.tee(gen)
for j in gencopy:
print(i, j)
Gives the following output:
(1, 2, 3) (1, 2, 4)
(1, 2, 3) (1, 2, 5)
(1, 2, 3) (1, 3, 4)
(1, 2, 3) (1, 3, 5)
(1, 2, 3) (1, 4, 5)
(1, 2, 3) (2, 3, 4)
(1, 2, 3) (2, 3, 5)
(1, 2, 3) (2, 4, 5)
(1, 2, 3) (3, 4, 5)
Which means that only one of the i
s is iterated across.
However if I change the tee
line to:
_, gencopy = itertools.tee(gen)
I get the full set of expected pairs.
(Note: I have since figured out that the best way to perform this is to simply feed the generator back through itertools.combinations
to get back combinatorical pairs and avoid the performance issues that the documentation claims to be present with tee. However, I'm curious about the behavior of the for loop and why changing the generator in this manner is causing it to bail early.)