How to get the length of an itertools.product?

To implement Kevin’s answer for an arbitrary number of source iterables, combining reduce and mul:

>>> import functools, itertools, operator
>>> iters = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> functools.reduce(operator.mul, map(len, iters), 1)
27
>>> len(list(itertools.product(*iters)))
27

Note that this will not work if your source iterables are themselves iterators, rather than sequences, for the same reason your initial attempts to get the length of the itertools.product failed. Python generally and itertools specifically can work in a memory-efficient way with iterators of any length (including infinite!) so finding out lengths up-front isn’t really a case it was designed to deal with.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)