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)?
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.
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”.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With