18  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:

symbols = ["MSFT", "AAPL", "GOOGL", "AMZN", "NFLX"]

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

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

When we use a "for" loop, we have to fill in some slots. To understand the slots, see the following pseudocode:

for _________ in _________:
    _________
for EACH_ITEM in EXISTING_LIST:
    DO_SOMETHING_WITH_THAT_ITEM

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:

symbols = ["MSFT", "AAPL", "GOOGL", "AMZN", "NFLX"]

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

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

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

symbols = ["MSFT", "AAPL", "GOOGL", "AMZN", "NFLX"]

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

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

The "for" loop is an essential and foundational technique, which will form the basis of more advanced operations, such as mapping and filtering.