Let’s say that I have a list of tuples foo
(object, integer) and a list of objects bar
. The length of each of these parent lists is variable. How do I combine them into a single list of tuples, wherein each tuple is a unique combination of elements from each of the two parent lists?
-
Example 1:
foo = [(A, i)] bar = [X, Y] # missing magic expected_result = [(A, i, X), (A, i, Y)]
-
Example 2:
foo = [(A, i), (B, j)] bar = [X, Y] # missing magic expected_result = [(A, i, X), (A, i, Y), (B, j, X), (B, j, Y)]
-
Example 3:
foo = [(A, i), (B, j), (C, k)] bar = [X, Y] # missing magic expected_result = [(A, i, X), (A, i, Y), (B, j, X), (B, j, Y), (C, k, X), (C, k, Y)]
-
Example 4:
foo = [(A, i), (B, j)] bar = [X] # missing magic expected_result = [(A, i, X), (B, j, X)]
Preferably, I’d like to do this in one line, if possible. The order of the resulting list is unimportant, but the order of the elements within the tuples of that list need to be predictable.
In addition to trying various solutions using itertools.product
and zip
, I also looked at the answers to other similar questions, but I was unable to find the solution to this problem.
1