Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python nested looping Idiom

Tags:

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 ... ? : 
like image 948
cacti Avatar asked Dec 14 '12 19:12

cacti


People also ask

What does nested loop mean in Python?

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.

What is the meaning of nested loops?

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 }

What are the different nested loop available in Python?

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.


1 Answers

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 
like image 87
Bakuriu Avatar answered Sep 18 '22 16:09

Bakuriu