[Python] Can someone please explain to me how nested for loops work using this example. I don't understand how it works
In python is there an easier way to write 6 nested for loops? - Stack Overflow
Nested loops
Learning Python & having trouble with Nested For Loops
if you have a for loop that runs 10 times (for i in range(10)), then it executes 10 times. If you have a for loop inside of that for loop that runs 10 times, then you have a loop that runs 10 times each time the outer run runs. That means for every 1 iteration of the outer loop, the inner loop runs 10 times. In total, the inner loop will run 10 * 10 times, or 100 times.
Therefore, any code inside the inner loop will run 10x more than the outer loop. Not only that - if you had another loop inside the inner loop running 10 times, that inner loop would end up running 10 * 10 * 10 = 1000 times!
Therefore, the location of the print statement matters - if it's in the inner loop, it will run 100 times, and in the outer loop only 10. So it has quite a dramatic effect on the output.
More on reddit.comVideos
userInput = int(input())
for i in range(userInput):
for j in range(i,userInput):
print('*', end=' ')
print()input is: 3
the output is:
* * * * * * I have been looking at videos and different websites, but i cannot understand it.
If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.
from itertools import product
for y, x in product(range(3), repeat=2):
do_something()
for y1, x1 in product(range(3), repeat=2):
do_something_else()
This is fairly common when looping over multidimensional spaces. My solution is:
xy_grid = [(x, y) for x in range(3) for y in range(3)]
for x, y in xy_grid:
# do something
for x1, y1 in xy_grid:
# do something else