Pythonic way to iterate through multidimensional space?

Gelonida N gelonida at gmail.com
Tue Oct 7 02:10:05 EDT 2014


On 8/6/2014 1:39 PM, Tim Chase wrote:
> On 2014-08-06 11:04, Gayathri J wrote:
>> Below is the code I tried to check if itertools.product() was
>> faster than normal nested loops...
>>
>> they arent! arent they supposed to be...or am i making a mistake?
>
> I believe something like this was discussed a while ago and there was
> a faster-but-uglier solution so you might want to consult this thread:
>
> https://mail.python.org/pipermail/python-list/2008-January/516109.html
>
> I believe this may have taken place before itertools.product() came
> into existence.
>

Disadvantage of itertools.product() is, that it makes a copy in memory.
Reason ist, that itertools also makes products of generators (meaning of 
objects, that one can't iterate several times through)


There are two use cases, that I occasionaly stumble over:

One is making the product over lists(),
product( list_of_lists )

ex:

product( [ [1,2,3], ['A','B'], ['a', 'b', 'c'] ] )

the other one making a product over a list of functions, which will 
create generators

ex:
product( [ lambda: [ 'A', 'B' ], lambda: xrange(3) ] )


I personally would also be interested in a fast generic solution that 
can iterate through an N-dimensional array and which does not duplicate 
the memory or iterate through a list of generator-factories or however 
this would be called.







More information about the Python-list mailing list