Looping through a list

So we have these things called lists… what if we want to run some code on every item in a list? Would I be asking the question if it couldn’t be done?! :-p

In the same way we test to see if a value exists inside a list, we can use the for statement to allow us to run code for each value in that list.

starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]
for person in starwars:
    print( "Hello "+person )

We can combine the “for in” with the “if in” functionality to see if each value of one list appears in a second list. Example:

starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]
skywalkers = ["Luke", "Leah"]
for person in starwars:
    if person in skywalkers:
        print( person+" is a Skywalker")
    else:
        print( person+" is not a Skywalker")
print("all done!")

Exercise 1

Can you figure out how to do the following?

Exercise 2

Can you figure out how to do the following?