Understanding for loops in Python

A for loop takes each item in an iterable and assigns that value to a variable like w or number, each time through the loop. The code inside the loop is repeated with each of those values being re-assigned to that variable, until the loop runs out of items.

Note that the name used doesn’t affect what values are assigned each time through the loop. Code like for letter in myvar: doesn’t force the program to choose letters. The name letter just gets the next item from myvar each time through the loop. What the “next item” is, depends entirely on what myvar is.

As a metaphor, imagine that you have a shopping cart full of items, and the cashier is looping through them one at a time:

for eachitem in mybasket: 
    # add item to total
    # go to next item.

If mybasket were actually a bag of apples, then eachitem that is in mybasket would be an individual apple; but if mybasket is actually a shopping cart, then the entire bag could itself meaningfully be a single “item”.

Leave a Comment