michigansqllite123 - 5 months ago 6x
Python Question

# 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
``````

etc.

The funny part is: I got exactly what I want, however I really don't understand the logic. For the code I wrote, I would expect the following output:

``````1 1
2 2
3 3
4 4
5 5
``````

Why? Because by my idea I stated the following:

For each value
`i`
(left column) in box and for each value
`x`
(right column) print both.

In fact, the code I believe should act as:

``````for i,y in zip(box,box):
print(i,y)
``````

My question is, why did the nested for-loop in the function behave differently then I expected?

How did it know to create
`number * number`
rows?
How did it order the numbers as it has, what relation acutally happened there?

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 `i`is `1` `x` 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 be`2`, 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 list
print i, "this is the first loop" #for each different 'i' in box
for x in box: #it will go through all elements in the list
print x, "this is the second loop" #you will get all elements from the box
print (i,x) #this is what you get
``````
Source (Stackoverflow)