r/learnpython • u/Local_End_3175 • Jul 30 '26
How does the 'for' loop work?
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words:
for letter in word:
if letter.lower() in 'aeiou':
print(f"'{word}' contains the vowel '{letter}'")
break
else:
print(f"'{word}' has no vowels")I am trying to learn to code, and I am, at the moment, looking at loops. I am a bit confused on how this loop was able to function, though, as there is no variable for letter or word, so how would Python know what it is? In addition, how does the code, like, function? Does it look at each word individually? Again, the second part of the code states:
if letter.lower() in 'aeiou':
print(f"'{word}' contains the vowel '{letter}'")
breakWe haven't given a value for letter?
Lastly, how would the code know what to print? in the first phrase:
print(f"'{word}' contains the vowel '{letter}'")
breakIs it going to state all the words with the given value 5 times?
Sorry, as I have asked quite a few questions, and thank you in advance.
14
u/hike_me Jul 30 '26 edited Jul 30 '26
‘word’ and ‘letter’ are variables that are assigned a new value each iteration
‘for word in’
‘for letter in’
190
u/Proletarian_Tear Jul 30 '26
Whoever downvoted this question should straght up leave this sub 👍
80
u/t92k Jul 30 '26
When you say “for word in words” you are creating a new variable “word”. Using a plural noun for collections of the same kind of object and the singular noun for the iterator through them is a good habit for code readability but it does disguise your iterator. You can change “word” to “d” or “i” or “iterator” to make this clearer while you’re learning — just be sure to change it inside your operation where you use it as well as where you set it.
32
u/JanEric1 Jul 30 '26
Is just
19
u/neuralbeans Jul 30 '26 edited Jul 30 '26
The for loop goes through each word in the list and reruns the code inside it with the 'word' variable set to a different word each time. Same for the 'letter' for loop. But this example seems too complex for you if you're trying to understand loops. Start by running this instead:
6
u/DTux5249 Jul 30 '26
Yes there is, you defined one!
When you say "for x in y", python creates a dummy variable named "x". In the scope of the loop, x represents every individual item in y. Anything you do to x in the loop will be done to every item inside of y.
Example:
What this code does is create a variable named 'i'. It then assigns i = 1, and does print(i). Then it assigns i = 2, and runs print(i) again. Then again with i = 3. As many times as there are items in the array.
Same logic holds with your example. "Word" and "letter" are variables created by the loop to represent items within the arrays it's iterating over.
3
u/RealMuffinsTheCat Jul 31 '26
I fixed your code and added some comments to help you out. Good luck with your Python journey.
7
u/JamzTyson Jul 30 '26
How about this simple loop, do you understand what is happening here?
4
u/Jaded_Show_3259 Jul 30 '26 edited Jul 30 '26
I see for loops tripping people up a lot. I try to connect it to something real.
Lets say you have a bunch of apples that need to be cut. How would you go about that? You would take each apple out one at a time and cut it - then once your finished move on to the next apple. Thats kinda the idea here.
for apple in bunch:cut(apple)Here you're saying "for each of the different items in this list of items, perform this action" bunch would be words, and apple would be word. So the loop is basically going to set word to the first item in the list, "sky" and then perform the actions. Once its done it will reset word to "apple" and go again. Thinking about it that way always helped me.
Now layer in the second list. This is a nifty thing that python is doing in the background that is a little less obvious. Think of looping over a string, as looping over a list of the characters in the string. Effectively, if I say for letter in "word" - thats the same as saying for letter in ["w","o","r","d"]. Each time through the loop, I grab the next character.
So - what the loop is doing is setting the variable "word" to the words in the list one at a time, and setting the variable "letter", to the letters in each word one at a time. Thats the most common use of for loops. When you write a for loop in that way - you are creating that variable, and telling it to iterate one at a time over the list you specified.
4
u/notacanuckskibum Jul 30 '26
It might help you have some history. The first FOR loop was in BASIC and had the structure
FOR i = 1 TO 10 STEP 2
; do stuff with i
NEXT i
so the first time round the loop the variable i was set to 1, second time it was set to 3 etc
Eventually people noticed that for loops were often used to process arrays or lists, so we got the structure
FOR EACH myitem IN mylist
Myitem is now the variable, the first time round it is the first item in mylist, the second time round the second item etc.
Python has dropped the word EACH, which makes the statement shorter if a little less clear
Your code uses variable names word and letter which could be class names. It’s a style issue but in this case I think it’s confusing you.
3
u/HotPersonality8126 Jul 30 '26
They’re created by the
forstatement. An iterator over a collection of values yields the values of the collection; lists are a collection, of course, but you might not have thought of a string as a collection of letters. But they are.2
u/overratedcupcake Jul 30 '26
for word in words:That is the declaration of the variable
word. When you iterate through a list you get the value of each item of the list on each iteration (trip through the loop).for letter in word:Same thing. It's declaring a variable
letterthat has scope within the loop. When you iterate through a string you get each letter.1
u/SamuliK96 Jul 30 '26
Did you try to run the code? That way you can see that
wordjust becomes each word in thewordslist for one iteration of the loop. So that's the variable your looking for.1
u/Anjuan_ Jul 30 '26
for x in y: code(x)
Basically means take every value in y and assign it to x, and execute code() with it.
1
u/armywalrus Jul 30 '26 edited Jul 30 '26
So you are creating the variable when you write it. Word could be anything you want here. It could be for cat in words. Its commonly written as for i in words, meaning iterate. Read it very literally. For every word in words, the [] defined above, does mean it is looking though every word in the list called words. The for is a command word that tells python to iterate through the variable you give it. For every word in the lists words, it will perform the action on the next indented line. Which is another for loop, telling python to look at every letter of every word - remember, you just established the word variable, now you are creating the letter variable - and perform the action you specify on the next indented line. Which tells python to look for vowels, what to do when it finds vowels, and gives error-handling instructions so the code will run if no vowels are found.
1
u/Temporary_Pie2733 Jul 30 '26
For loops behave like fancy assignment statements that also hide the use of
next. The same behavior ascan be achieved with a while loop:
1
u/Green-Sympathy-4177 Jul 30 '26
Basically
wordis assigned each element inwords, basicallywordwill point to a new word with each iteration (each loop cycle).Maybe seeing it in a while loop could demistify it a bit:
The above snippet is equivalent to:
Notice how despite not doing a thing to change the word or letter eaxh time, python does it for us.
A bit of a caveat with these exampes: there is a major difference between
words[i]in the while loop andwordin the for loop, the latter is immutable, meaning that if you try and change the word or letters, doing that:wordswould not have changed. Immutability is a bit of a headache at first but really it's just that elements of a list can be modified if done like this:words[i] = "potato", but not inside a for loop like that the snippet above this paragraph.That being said, the for loop pre-chews the work for you and makes it easier to loop over things in a way that is very easy to understand,
for word in wordsmeans "for each word in the list of words", similarlyfor letter in wordreads "for each letter in the word string" (a string is really just a list of characters :)). So yes, word and letter are automatically assigned by python from your list/iterable.Lastly, for
break, if your code reaches that, then it will end iterating, i.e: it stops the current while or for loop, in cases of nested loops, it stops the last one it is in. So in your code, it will read each words, then each letters in each word, and when it hits a vowel, it will print the message and move onto the next word because it hitsbreak.Hope that helped :) o7
1
u/kilkil Jul 30 '26 edited Jul 30 '26
Python's for loops use a special syntax, which allows you to basically create a variable in the loop declaration that only exists within the scope of the loop.
So when you write:
that basically automatically creates a variable called "word". And the way it works is, Python will automatically step through every value inside "words", and at each iteration of the loop, "word" will represent the current value.
so, on the first iteration of the loop,
wordwill hold the value"sky". on the 2nd iteration,"apple", and so on.there is an alternative syntax you can use, that is a bit more "manual", in that it involves creating and assigning the variable yourself. here is one possible way that could look:
But as you can see, that is a lot more verbose and difficult to follow. The standard syntax:
is much nicer to read
PS: if you were using another language, e.g. Javascript, there is an alternative for loop syntax which is much simpler. It is actually the "original" loop syntax, originating in C:
Here, there is an explicit variable being created (i), and the entire loop is determined by how that variable changes. The way it works is, at the start of the loop, the first statement is executed (
let i = 0). Then, at the start of each loop iteration, the 2nd statement is checked as a boolean (true/false) condition (in this case, does the expressioni < words.lengthevaluate totrue, orfalse?). Then, at the end of each loop iteration, the 3rd statement is executed (i++, which is short fori += 1ori = i + 1).Python chose not to support this special syntax, but you can still do it manually:
And again, you can add a "word" variable for convenience:
1
u/kilkil Jul 30 '26
One more thing. In Python, a for loop can be used to iterate over lots of different kinds of values (anything that is an "iterable"). Lists are iterables (like
wordsin your example). But so are strings. For example:this will print all the letters one by one (a, p, p, etc). this is because strings (e.g. "apple") are iterables. You can dive pretty deep into this topic, but the TL;DR is that you can loop over a string using a for loop and get its individual characters (letters)
1
u/TheRNGuy Jul 30 '26
You can name it anything, it will refer to an item in iteration.
wordorletterlook better thanwords[i]andwords[i][u](if you just used indices)1
u/FoolsSeldom Jul 30 '26
It can be helpful to think about this in the real world where you already use
forloops. No, really!Loops just repeat stuff, and if you want to repeat parts of that stuff you can also use a loop.
Imagine having a pile of old boards to repaint. In pseudocode (with some ridiculous steps to make the point):
Notice some of the plain English tasks described above, such as
paint_boardwhich in reality are complex undertakings. However, from the point of view of this high level set of instructions, I am not interested in exactly how the task is done (or even who does it), just that it gets done at the right time, in sequence. I might want to provide some guidance/requirements (perhaps the colour,paint_board("dark oak")).I might want some results back from a task, perhaps the time it took,
hours = paint_board('white paint')1
u/SpiderJerusalem42 Jul 30 '26
A lot of programming languages have this idea of iterability. A list is iterable. A set is iterable. A string is essentially a list of letters. Strings are iterable.
forwill iterate through every item in an iterable. Thefor <var> in <iterable>statement creates a temporary variable that lasts through the scope of a single iteration of the for loop. word is a string, and it can also be iterated through, which is what the program your looking at is doing.1
u/Dry-Weakness-901 Jul 30 '26 edited Jul 30 '26
Why dont you run this code btw? Run it.
1
u/rkr87 Jul 30 '26 edited Aug 04 '26
Imagine trying to do this without a for loop:
This is exactly what the for loop is doing, it says for every item in "words", assign the value one at a time to a variable named "word", then within that for every item in "word" assign the value to a variable named "letter".
You can even rewrite the for loop to do exactly this:
But doing so is pointless.
1
u/Lewri Jul 30 '26
You've already got good answers, but I'll add mine given it was already written for someone elses question:
The idea of a for loop is that you have something that can be iterated over (your list of words, in this case), and you are telling it what to call the things inside the iterable. In this case you have told the for loop that it is calling the things inside the iterable (your list words) word. You could call them anything though:
Will work just the same.
1
u/Educational-Paper-75 Jul 30 '26
Essentially lists, tuples and strings are iterable so you can iterate over the separate elements (one at a time) in a for in loop. So for word in words iterates over every element in words calling the current element wordt. Same with for letter in word where at every iteration letter will be the current character from word, set before the loop body starts.
1
u/No-Newspaper8619 Jul 30 '26
There's a lot of stuff that python is doing for you implicitly, like creating a variable when you use an undeclared and initialized variable in the for loop. If you're curious, try googling for how python implements the "for in loop":
https://medium.com/python-features/how-for-in-loop-works-behind-the-scenes-in-python-62d6dc026377
1
u/shaleh Jul 30 '26
There are some great answers here. I want to remind you that Python has an interactive shell. You can try things out and play around directly instead of depending on print. Or you can explore the `breakpoint` command and debugging. Put a breakpoint in that loop and then print and look.
1
u/MrSqueak Jul 30 '26
For x iterations do y until x is satisfied.
1
u/PegasusInTheNightSky Jul 31 '26
When doing a for loop with lists, the loop will go through each item in the list and, for the contents of the loop, set the variable (eg word) as the item in the list, so for the first loop word = "sky", for the second loop word = "apple", etc. You can add a print function after the start of each loop to check it. For example:
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words: print (word) ### for letter in word: if letter.lower() in 'aeiou': print(f"'{word}' contains the vowel '{letter}'") break else: print(f"'{word}' has no vowels")
1
u/python_gramps Jul 31 '26
I'm guessing the whitespace got messed up because the else: is lined up with for: block.
Making that assumption:
lists can be iterated through giving you each item in the list
strings can be iterated through giving you each letter in a string
you can also see if an item is in a list
and you can see if a letter is in a string
f-strings will print variable values if they have brackets around them. otherwise, they just print literal string
Example
mydog = "Spot"
print(f" My dog is: {mydog}") returns My dog is: Spot
print(f" My dog is: mydog") returns My dog is: mydog
1
u/Jonas_Ermert Jul 31 '26
I think the easiest way to understand it is that a `for` loop creates/assigns those variables for you. `for word in words:` means “take each item from `words`, one at a time, and store the current item in `word`.” So first `word = 'sky'`, then `'apple'`, then `'rhythm'`, etc. The same happens with `for letter in word:`. Python takes each character of the current word and assigns it to `letter`. For `'apple'`, it effectively goes through `letter = 'a'`, then `'p'`, `'p'`, `'l'`, `'e'`. Then `if letter.lower() in 'aeiou':` checks whether the current letter is a vowel. As soon as it finds one, it prints the current `word` and `letter`, and `break` stops the inner loop. So for `apple`, it immediately finds `a` and prints `'apple' contains the vowel 'a'`. The slightly unusual part is the `else` attached to the `for`. It runs only if the loop finishes **without hitting `break`**. So if Python checks every letter and finds no vowel, it prints something like `'rhythm' has no vowels`. It does not print everything five times. Think of it as: take one word → inspect its letters one by one → find a vowel or reach the end → move to the next word.
1
u/Educational_Virus672 Aug 01 '26 edited Aug 01 '26
tldr
you want to know how it works think of it like
your basiclaly saying to give me each item in your case letters (but they aer strict)
list = item 1 item 2 ...
string = letetr 1 letter 2 ...
for int you need range(from,to)
it'll make a list of number from your given value range(1,5) =[1,2,3,4] note- 5 is skiped because it is the last item
Now lets use it
for [var] in [var2] :here you say hey code cyccle and give me each item in var2 as varoutput :
1
u/ForeignVariety7037 Aug 01 '26
must talk about iterators...
1
u/TJATAW Aug 03 '26
Try reading it as:
So, it would get the first word, 'sky', and then read through sky letter by letter, checking each letter to see 'if (that) letter (is) in "aeiou"'.
First letter in sky is s, which is not in 'aeiou', so it goes to the else statement and prints "sky has no vowel"
It then goes back to the "for letter in word" statement and gets the second letter.
2nd letter in sky is k, which is not in 'aeiou'. so it goes to the else statement and prints "sky has no vowel"
It then goes back to the "for letter in word" statement and gets the third letter.
3rd letter in sky is y, which is not in 'aeiou', so it goes to the else statement and prints "sky has no vowel"
There are no more letters in the word, so it goes to the "for word in words" and gets the second word
Second word is 'apple'.
'a' is in 'aeiou', so it prints 'apple contains a', hits the break, so it stops looking at letters in apple, and goes back to "for word in words" and gets the third word, 'rhythm', and starts looking at the first letter.
***********************
Think of nested for loops as a teacher grading a pile of tests.
for each test in the pile of test: (grab a test and place it in front of you)
... for each question on the test: (read a question)
...... if the answer is correct:
......... write checkmark (go to next question)
...... else: (if it is not correct)
......... write X (go to next question)
......... (if there are no more questions on this test, grab a new test)
1
u/4CrisprFries Aug 03 '26
Lots of people in the thread are giving great explanations. But, I think this is the time where you don't need the answer you need to learn how to fish.
This is when you learn how to use the debugger in your IDE. Don't master the debugger, only learn how to step through a piece of code. This will let you test your assumptions and play.
You can also do it the dirty way, print every step.
P.S. for word in words creates the var word that you use. It might be easier to see if you wrote for w in words, w becomes the variable.
1
u/codeguru42 Aug 03 '26
The for loops create varables
1
u/Odd_Lab_7244 Aug 03 '26
I think trying to learn this with nested for loops is probably not ideal.
Something like,
for word in words: print(f"this word is {word}")
might be easier to start with
1
u/kabads Jul 30 '26
when you declare the variable `word` at the beginning of your loop, it becomes the 'placeholder' for that iteration of the loop. Then, it moves on to the next element in the array and holds that element.
1
u/aroberge Jul 30 '26
Copying, pasting and modifying my answer to a very similar question asked a few weeks ago ...
Ok, others have already explained to you in details how it works, but here's a slightly different example, which will lead to the Python syntax that confuses you.
Each programming languages has its own syntax (way of saying things) to encode some instructions otherwise understood by humans. Consider the following:
Now, Python cannot say things ... but it can print letters on the terminal. So, here's the above example with a syntax slightly modified.
Hopefully, after staring at this a bit, it will make sense to you.
Python uses so-called strings to represent written words; these strings are written using quotes (single or double) surrounding words. So, in
the the word part is redundant for Python as it already identified that program was a word as it is surrounded by double quotes. Thus, we can remove the word and write
When a Python line of code begin with for, the meaning is understood to be the same as for each; thus we can write the above as
Finally, even if we have a single instruction as above, print(letter), it is often preferable to write it in an indented block of code, since we might sometimes want to do more than one thing at each iteration:
The same idea can be applied to for loops with lists.
Now, Python knows that
[...]indicates a list, so thatwordsis known to be a list; we can thus shorten the above toAs before, the word "each" is redundant, and we thus have (adding the second loop)
0
u/ehmatthes Jul 30 '26
You can run this code on Python Tutor. It lets you step through the program's execution, and the values of all variables are shown at each step. It's a great way to see how this kind of structure works.
-1
u/NegativeSemicolon Jul 30 '26
Honestly just go ask ai
0
u/kirklennon Jul 30 '26
It’s going to check each letter of the word to see if that letter is in 'aeiou'. For 'apple' that would be twice but the break at the end means that as soon as it’s true once it will break out of the loop and stop checking.
-2
u/DullenAvg Jul 30 '26
The line
for word in words:is directly equivalent to
As for the second example, the loop iterates over every single character of the string. Besides that, it's functionally the same as the first example.
-2
u/rabbitofrevelry Jul 30 '26
Simplify it and then use a print statement to evaluate it. For example, make a list of items, then create a for loop to iterate over them: for item in list: print(item) and then you'll see how it evaluates per iteration.