Python Python Basics (2015) Logic in Python Loop

charles liscomb
charles liscomb
2,074 Points

How does a for loop know what is in an array when it's not defined?

In the section of my code below, I do not understand how this works. When I think about this code, I interpret this as "For every time word in found within the hellos array, we are going to print the word and a string". Yet, at no point does this code define what "word" is. How does Python know what we are looking for within the array?

This would make sense if we created a variable and defined what "word" was, but this isn't done and I am having difficulty understanding how it works.

for word in hellos print(word + " World")

loop.py
hellos = [
    "Hello",
    "Tungjatjeta",
    "Grüßgott",
    "Вiтаю",
    "dobrý den",
    "hyvää päivää",
    "你好",
    "早上好"
]

for word in hellos:
    print(word + " World")

2 Answers

Steven Parker
Steven Parker
163,772 Points

The "for" statement defines "word" as the variable it will use to represent each item of the iterable "hellos". And since variables in Python are not typed, it really doesn't matter what "hellos" contains. If you've programmed other languages before, it may take some getting used to before you can "think in Python".

For each pass through the loop, "word" will be assigned to one of the strings in the array. Each one is used in the order it is found. Nothing is "looked for".

andren
MOD
andren
Treehouse Moderator 28,327 Points

Your understanding of how a for loop works is slightly off.

The way it actually works is that the for loop will take the list you give it and then assign each item of the list to the variable you tell it to create. So the first time the loop runs it will pull out the first item of hellos and assign it to item then run the code, then it will pull out the second item of hellos and assign it to item and then run the code again. It continues this routine until it has gone though all of the items in the list and then the loop stops on it's own.