Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic shortcut for doubly nested for loops?

Consider if I had a function that took a tuple argument (x,y), where x was in the range(X), and y in the range(Y), the normal way of doing it would be:

for x in range(X):
    for y in range(Y):
        function(x,y)

is there a way to do

for xy in something_like_range(X,Y):
    function(xy)

such that xy was a tuple (x,y)?

like image 542
Bolster Avatar asked Mar 28 '11 16:03

Bolster


People also ask

Is there 2 for 2 loops?

Two nested for loops: O(n²) In the above nested loop example, outer loop is running n times and for every iteration of the outer loop, inner loop is running (n - i) times.

Can you do a double for loop in Python?

In Python, you can simply use a loop inside the loop to get double loops. In Double-loop The “inner loop” will be executed one time for each iteration of the “outer loop”.

Can you have two for loops in same line Python?

Summary. Python for loop is used to iterate over a sequence such as string, list, tuple, or any other iterable objects such as range. We can use as many for loops as we want along with conditions. Python allows us to write for loops in one line which makes our code more readable and professional.


1 Answers

You can use product from itertools

>>> from itertools import product
>>> 
>>> for x,y in product(range(3), range(4)):
...   print (x,y)
... 
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(1, 0)
(1, 1)
(1, 2)
(1, 3)

... and so on

Your code would look like:

for x,y in product(range(X), range(Y)):
    function(x,y)
like image 111
Mike Lewis Avatar answered Sep 23 '22 02:09

Mike Lewis