Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested for loops in Python compared to map function

Tags:

python

loops

I'm working in python and currently have the following code:

list = []
for a in range(100):
    for b in range(100):
        for c in range(100):
            list.append(run(a,b,c))

where run(a,b,c) returns an integer (for example, it could multiply the three numbers together). Is there a faster way to either loop over these numbers or use a map function?

Thanks :)

like image 623
Codahk Avatar asked Dec 21 '22 09:12

Codahk


1 Answers

Have a look at the itertools-module and particulary the product method

example usage:

for i in itertools.product(range(0,100), repeat=3):
    #do stuff with i
    list.append(run(i[0],i[1],i[2]))

Note that the function call can be shortened to:

list.append(run(*i))

in the example above. see docs.python.org for explanation of Unpacking Argument Lists.

As an example, the output from product(range(0,2), repeat=3)) looks like this:

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
like image 127
Fredrik Pihl Avatar answered Dec 24 '22 02:12

Fredrik Pihl