I want something like code below, but "pythonic" style or using standard library:
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
I want something like code below, but "pythonic" style or using standard library:
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
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)
A question we might ask is whether you want to generate all ordered pairs or all unordered pairs. The nested generator expression provided in the answer by mhyfritz will give you all ordered pairs.
If you want all unordered pairs (that is, (1, 2) and (2, 1) counts as the same pair), then you need to filter out the duplicates. An easy way to do this is to add a conditional to the end of the generator expression like so:
myList= [1, 2, 3, 4, 5]
unorderedPairGenerator = ((x, y) for x in myList for y in myList if y > x)
for pair in unorderedPairGenerator:
print(pair)
#(1, 2)
#(1, 3)
#(1, 4)
#(1, 5)
#(2, 3)
#(2, 4)
#(2, 5)
#(3, 4)
#(3, 5)
#(4, 5)
As an aside, I was given a question similar to this in a software interview, where they wanted me to generate all pairs from a list of numbers (without using a library function). At first I generated all the ordered pairs, and then they asked me to only generate the unordered pairs. Being able to work with permutations and combinations is a pretty essential coding skill!