How does Python know what character my loop variable currently is?


#1

Question

How does Python know what character my loop variable currently is?

Answer

When we create a for loop and create some named variable after the word for, Python knows to assign that variable the value of each thing we’re iterating over in the iterable object given to the for loop after the word in.
For example, if we have for character in some_word:, character will hold the value of each individual character until there are no characters left in some_word.
It doesn’t “know”, by any means. Python just expects something it can iterate through, and then assigns each current item to the variable and that’s what you’re given to work with.


FAQ: Learn Python- Loops - For your strings