Pythonic way to iterate through multidimensional space?

Chris Angelico rosuav at gmail.com
Wed Aug 6 02:25:44 EDT 2014


On Wed, Aug 6, 2014 at 3:34 PM, Gayathri J <usethisid2014 at gmail.com> 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? any idea?

Don't worry about what's faster. That almost never matters. Worry,
instead, about how you would code it if you can't be sure how many
dimensions there'll be until run time (which the OP said can happen).
With product(), you can give it a variable number of arguments (eg
with *args notation), but with loops, you'd need to compile up some
code with that many nested loops - or at best, something where you cap
the number of loops and thus dimensions, and have a bunch of them
iterate over a single iterable.

ChrisA



More information about the Python-list mailing list