Or equivalently, how to unpack elements of a sequence of variable length?
I'm trying to write a function to return the Cartesian product of all the tuples inside a list (the list has a variable length):
Input: [(1, 2), (3,), (5, 0)]
Output: [(1, 3, 5), (1, 3, 0), (2, 3, 5), (2, 3, 0)]
But the problem is that I'm unable to pass all the tuples to the itertools.product()
function. I thought of unpacking the elements inside an equivalent user-defined function, but I can't figure out how to do that for a variable list.
How can I define this function?
CodePudding user response:
I think itertools.product
would work fine here, unless I am missing something.
>>> from itertools import product
>>> l = [(1, 2), (3,), (5, 0)]
>>> list(product(*l)) # unpack the list of tuples into product
[(1, 3, 5), (1, 3, 0), (2, 3, 5), (2, 3, 0)]
In Python *
and **
can be used as packing/unpacking operator wrt iterables. Here is an example of unpacking:
# Suppose you have a few variables, of which one (b) is an iterable
>>> a = 1
>>> b = [2, 3, 4]
>>> c = 5
# Now you can make a new list with a, b, and c
>>> list1 = [a, b, c]
>>> list1
[1, [2, 3, 4], 5]
# Notice how b stays a list inside the new list.
# If we need the individual elements of b, we can use unpacking
>>> list2 = [a, *b, c]
>>> list2
[1, 2, 3, 4, 5]
Similarly, as product
needs the iterables to be passed as separate arguments, we can make use of unpacking. You can learn more about unpacking in PEP 448, PEP 3132.