Skip to content Skip to sidebar Skip to footer

How Do Nested For Loops Work?

This is the code I wrote, works perfectly fine: box = [1, 2, 3, 4, 5] for i in box: for x in box: print (i,x) It outputs the following: 1 1 1 2 1 3 1 4 1 5 2 1 2 2 e

Solution 1:

It is logic. for i in box, i will start being 1 and moving forward until being 5 (all elements from the list). So if you print i inside this loop, you will see that i is first 1, then i is 2 ... until i is 5 (last element from box). But if you nest another for loop, it will do the same (start from 1 and moving forward until 5) for each time i is a different element from the list. So when i is 1, before changing to another different i it will start the second loop (for x in box), so then when iis 1x will change being x == 1, x == 2... x == 5. When this nested loop finishes, then i changes to another element from the list, so now i would be2, and the nested loop starts again, so x == 1, x == 2..., x == 5.

I think you might understand how it works if you try this

box = [1, 2, 3, 4, 5]


for i in box: #it will go through all elements in the listprint i, "this is the first loop"#for each different 'i' in boxfor x in box: #it will go through all elements in the listprint x, "this is the second loop"#you will get all elements from the boxprint (i,x) #this is what you get

Solution 2:

You've got a loop within your loop, so this inner loop will run in its entirety for each iteration of the outer loop. So for each number of i, you need to go through the entire loop for x.

Solution 3:

This:

box = [1, 2, 3, 4, 5]
foriinbox:
    forxinbox:
        print (i,x)

Is the same as this:

i = 1forxinbox:
    print (i,x)
i = 2forxinbox:
    print (i,x)
i = 3forxinbox:
    print (i,x)
i = 4forxinbox:
    print (i,x)
i = 5forxinbox:
    print (i,x)

Solution 4:

If this is what you want


1 1
2 2
3 3
4 4
5 5

then do this:


for i in box:
    print(i,i)

If you do this:

foriinbox:
    forxinbox:
        print (i,x)

then after the outer loop is executed once, it will execute the inner loop until the inner loop is COMPLETE. That means for 1 outer loop, inner loop will be executed for 5 times. the logic is like this:

  • i will retrieve the value of the first element of the box arrray
  • x will retrieve the value of the first element of the box arrray
  • Then 1 1 will be printed
  • x will retrieve the value of the second element of the box array
  • Then 1 2 will be printed
  • x will retrieve the value of the third element of the box array
  • Then 1 3 will be printed. And so on until 1 5 is printed
  • i will retrieve the value of the second element of the box array
  • x will retrieve the value of the first element of the box arrray
  • Then 2 1 will be printed
  • x will retrieve the value of the second element of the box array
  • Then 2 2 will be printed and so on

Post a Comment for "How Do Nested For Loops Work?"