Reputation: 99
I have this nested loop:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
From reading it I was expecting the output to be:
red apple
big banana
tasty cherry
Can somebody please explain to me why I am getting?
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
I am really confused and can't work it out!
Many thanks!
Upvotes: 1
Views: 1013
Reputation: 186
You are first selecting x = 'red'
, and printing it with every fruit by assigning each fruit to y
in the inner loop.
Then you are selecting x = 'big'
, and printing it with every fruit by assigning each fruit to y
in the inner loop, and so on.
To get the output you are looking for, you need to first zip the lists together and then print in a loop.
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
adj_fruits = zip(adj, fruits)
for name in adj_fruits:
print(name[0], name[1])
Output:
red apple
big banana
tasty cherry
Upvotes: 1
Reputation: 670
You loop over the first list, and for each item in the first list you loop over all the items in the second list.
So it goes...
adj[0], fruits[0] # red apple
adj[0], fruits[1] # red banana
adj[0], fruits[2] # red banana
adj[1], fruits[0] # red apple
etc..
You could try to get a more clear picture of whats going on under the hood by by using enumerate
, but it's a little more complex and could end up just making things more difficult.
for adj_index, adjective in enumerate(adjectives):
for fruit_index, fruit in enumerate(fruits):
print(f' {adjective} at {adj_index} and {fruit} at {fruit_index}')
And as Karl Knechtel mentioned in his answer, you could use zip
to iterate over the lists at the same time.
for adj, fruit in zip(adj, fruits):
print(adj, fruit)
Upvotes: 2
Reputation: 61478
Everything inside a loop happens each time the loop runs (notwithstanding the things that could short-circuit or exit the loop: break
, continue
, return
from the enclosing function, or raising an exception not caught locally, or anything that forces the program to quit immediately such as pulling out the power plug :) )
The inner loop is inside the outer loop (that's what it means for them to be nested), so the entire inner loop happens, separately and over again, for each time through the outer loop.
The first time the outer loop runs, x
is set to 'red'
. So that value is used for each iteration of the inner loop, and thus paired up with each of the y
values. And so on for the rest of the iterations.
If you want the behaviour you were expecting, please see How to iterate through two lists in parallel?.
Upvotes: 3