+ 1

Could someone pleases explain why this happens?

words = ["hello", "world", "spam", "eggs"] for i in words: print(i + "incheese") in the code above, each item in the list is printed as normal with "incheese" at the end, however: words = ["hello", "world", "spam", "eggs"] for i in words: print(i + "!") print(i + "incheese") in this second piece of code when I do, print(i + "incheese"), only the last item in the list (i.e eggs) is printed out. Why is that?

18th Jul 2018, 4:35 PM
Henderson
Henderson - avatar
8 odpowiedzi
+ 2
I, the variable of the for-loop, changes with every iteration; after the loop ended, it remains what it was in the last iteration. So if you want to do your command for the whole list, you either put it into the for-loop or you write a new for-loop - then i gets redefined as the first list element.
18th Jul 2018, 4:52 PM
HonFu
HonFu - avatar
+ 1
for i in '!', 'incheese' : for j in words: print (j+i)
18th Jul 2018, 5:09 PM
HonFu
HonFu - avatar
0
It was because the print(i + "incheese") is out-dented meaning it is not a part of the "for i in words" loop
18th Jul 2018, 4:46 PM
Ipang
0
but why is it only the last item printed? why isn't the first, second or third?
18th Jul 2018, 4:48 PM
Henderson
Henderson - avatar
0
It's because the iterator (i) is pointing at the last item, because the loop has completed when you do print(i + "incheese"). Put the print(i + "incheese") statement at the same indentation level as the print(i + "!") then you will see ...
18th Jul 2018, 4:53 PM
Ipang
0
great it work, another question though: Is there I can make each all the words in the second loop come after the first -- hello! world! spam! eggs! helloincheese worldincheese spamincheese eggsincheese instead of what comes out now: hello! helloincheese world! worldincheese spam! spamincheese eggs! eggsincheese
18th Jul 2018, 5:02 PM
Henderson
Henderson - avatar
0
Make two loops, first to print i + "!" and second to print i + "incheese"
18th Jul 2018, 5:07 PM
Ipang
0
Alright, thank you!
18th Jul 2018, 5:12 PM
Henderson
Henderson - avatar