I often find myself doing this:
for x in range(x_size): for y in range(y_size): for z in range(z_size): pass # do something here
Is there a more concise way to do this in Python? I am thinking of something along the lines of
for x, z, y in ... ? :
What is a Nested Loop in Python? A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type, such as a while loop or for loop. For example, the outer for loop can contain a while loop and vice versa. The outer loop can contain more than one inner loop.
Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“. Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop }
Nested for Loops in Python You can put a for loop inside a while, or a while inside a for, or a for inside a for, or a while inside a while. Or you can put a loop inside a loop inside a loop.
You can use itertools.product:
>>> for x,y,z in itertools.product(range(2), range(2), range(3)): ... print x,y,z ... 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 1 0 0 1 0 1 1 0 2 1 1 0 1 1 1 1 1 2
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