itertools.product - fast C code; np.array is a slower general purpose code. np.fromiter can be faster in the right situations. But fromiter requires flat input, not nested lists. But another itertools great job of smoothing lists.
Here are some examples of time:
In [72]: timeit list(product([0,1],repeat=5)) 100000 loops, best of 3: 7.03 us per loop In [73]: timeit list(chain(*product([0,1],repeat=5))) 100000 loops, best of 3: 18.3 us per loop In [74]: timeit np.fromiter(chain(*product([0,1],repeat=5)),int,count=160).reshape(-1,5) 10000 loops, best of 3: 33.8 us per loop In [75]: timeit np.array(list(product([0,1],repeat=5))) 10000 loops, best of 3: 65.1 us per loop
In this case, including count win fromiter , doesn't really matter.
There is a certain pythonian elegance in chain generators.
As a comparison, my time for the pure numpy method is a bit slower:
In [85]: timeit (((np.arange(2**5)[:,None] & 2**np.arange(5)[::-1]))>0).astype(int) 10000 loops, best of 3: 38.1 us per loop
But @Divakar shows that this solution scales much better.
hpaulj
source share