Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Iterate both i and j in Python

Two methods for implimenting nested iterations of i and j in Python.

The following pieces of code can be used where there is a need to iterate over values of both i and j in Python. The first method uses a while clause:

i = 1
while i < 4:
    j = 1
    while j < min(i+2, 4):
        print "i={};j={}".format(i, j)
        j += 1
    i += 1

The second method uses a for loop:

for i in range(0,4):
    for j in range(0,4):
        print("i={};j={}".format(i, j))
print("Complete")

Output will be as follows:

i=0;j=1
i=0;j=2
i=0;j=3
i=0;j=4
i=1;j=1
i=1;j=2
i=1;j=3
i=1;j=4
i=2;j=1
i=2;j=2
i=2;j=3
i=2;j=4
i=3;j=1
i=3;j=2
i=3;j=3
i=3;j=4
i=4;j=1
i=4;j=2
i=4;j=3
i=4;j=4
Complete
   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.