+ 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?
8 Answers
+ 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.
+ 1
for i in '!', 'incheese' :
for j in words:
print (j+i)
0
It was because the print(i + "incheese") is out-dented meaning it is not a part of the "for i in words" loop
0
but why is it only the last item printed? why isn't the first, second or third?
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 ...
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
0
Make two loops, first to print i + "!" and second to print i + "incheese"
0
Alright, thank you!