Bottom line, itertools.product
is already an iterator. You don't need to write your own. (A generator is a kind of iterator.) For example:
>>> x = [[1, 2], [3, 4]]
>>> p = itertools.product(*x)
>>> next(p)
(1, 3)
>>> next(p)
(1, 4)
Now, to explain, it seems like you're misunderstanding something fundamental. A generator function returns a generator iterator. That's what you're seeing from the print:
>>> iter_tools(*x)
<generator object iter_tools at 0x7f05d9bc3660>
Use list()
to cast an iterator to a list.
>>> list(iter_tools(*x))
[[(1, 3), (1, 4), (2, 3), (2, 4)]]
Note how it's a nested list. That's because your iter_tools
yields one list then nothing else. On that note, that part makes no sense because casting itertools.product
to a list defeats the whole purpose of an iterator - lazy evaluation. If you actually wanted to yield the values from an iterator, you would use yield from
:
def iter_tools(*array):
yield from itertools.product(*array)
In this case iter_tools
is pointless, but if your actual iter_tools
is more complex, this might be what you actually want.
See also:
This answer is partly based on juanpa.arrivillaga's comment
itertools.product(*array)
is already an efficient iterator. There is no need to wrap it in an generator. So just useitertools.product(*array)
. Your generator does work, generator functions return generators. It seems like you have a fundamental misunderstanding. – Pitchstone