Could someone, please, explain to me the logic of this result?
wizard_list = ['cup', 'tea', 'knife', 'bread']
for i in wizard_list:
print(i)
for q in wizard_list:
print(q)
The result:
cup
cup
tea
knife
bread
tea
cup
tea
knife
bread
knife
cup
tea
knife
bread
bread
cup
tea
knife
bread
I expected:
cup
cup
tea
tea
knife
knife
bread
bread
CodePudding user response:
You are iterating through each item and then whole list again per item.
wizard_list = ['cup', 'tea', 'knife', 'bread']
for i in wizard_list:
print(i)
print(i)
The above code will give you your desired result of printing twice.
CodePudding user response:
Since wizard_list
contains 'cup', 'tea', 'knife', 'bread'
, that means that if you have a for
loop like for x in wizard_list
, the loop is going to iterate through 'cup', 'tea', 'knife', 'bread'
. You're doing that in your outer loop, meaning i
will at some point be each item in wizard_list
. However, since you're doing another identical loop within the outer one, q
will also loop through each item in the list. And because it's a loop within a loop, every value in wizard_list
will be printed via the q
loop before the i
loop moves to the next item.
For example, on the first iteration, i
is 'cup'
. So, print(i)
will print cup
. The next line is the q
for loop. The line after that is print(q)
, and since you're now looping through wizard_list
in the q
for loop, q
will be set to 'cup'
as well, and thus that will be printed.
After that, q
moves onto the next item, 'tea'
. Since a loop starts from the beginning, the line print(q)
is reached again. So, so far you've printed cup
, cup
, and tea
. The q
for loop will continue printing all the items until bread
is printed. At that point, the q
loop ends because it reached the end of wizard_list
. Thus, i
will then be set to the next item in the list, 'tea'
, and the q
loop will start over, starting from 'cup'
.
So, the end result is that for each item in the list, you print all the items in the list.