List Iteration and Looping

Recall our example list from earlier:

symbols = ["MSFT", "AAPL", "GOOGL", "AMZN", "NFLX"]
print(type(symbols))
print(symbols)
<class 'list'>
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX']

We saw how we can print and access all items at once. And we saw we can use an index reference to access a specific item. But what if we want to access each item individually, however many there are?

We can use a "for" loop to access each item one at a time:

print("TOP")

for item in symbols:
    print("--------")
    print(item)
    # NOTHING ELSE, GO TO NEXT ITEM

print("BOTTOM")
TOP
--------
MSFT
--------
AAPL
--------
GOOGL
--------
AMZN
--------
NFLX
BOTTOM

When we use a "for" loop, we have to fill in some slots. We have no choice but to put the list we want to loop through in the second slot (after the in). But we have an absolute arbitrary choice of what variable name to use to reference each item (after the for). Whatever variable name we choose (e.g. x), we must also reference that variable within the scope of the loop:

print("TOP")

for x in symbols:
    print("--------")
    print(x)
    # NOTHING ELSE, GO TO NEXT ITEM

print("BOTTOM")
TOP
--------
MSFT
--------
AAPL
--------
GOOGL
--------
AMZN
--------
NFLX
BOTTOM

In practice, if we have a list of items plural (symbols), we could call each item the singular version (symbol) to make our code readable:

print("TOP")

for symbol in symbols:
    print("--------")
    print(symbol)
    # NOTHING ELSE, GO TO NEXT ITEM

print("BOTTOM")
TOP
--------
MSFT
--------
AAPL
--------
GOOGL
--------
AMZN
--------
NFLX
BOTTOM

Loops are essential and foundational. They will form the basis of more advanced operations, such as mapping and filtering.