Lists with a FOR Loop

Now you have learned how to use a list and how to write a for loop you will see that lists and for loops go together like bread and cheese!

For example:

1
2
3
def print_crops():
    for crop in ["wheat", "rye", "maize", "linseed"]:
        print(crop)

In the example above each is used to work through the list, printing out each item in turn. Watch this demonstration:


Exercises

  1. Write a function which finds the largest of a list of numbers. Set up the list as the first line in your program.

    Tip: create a variable called max, and compare every value in the list with max.

  2. Write a function which finds all the words beginning with “s” in a list and prints them out. It also should say how many words it has found beginning with “s”. Again, set up the list in the first line of the program.

  3. Write a function which finds the average of a list of numbers using a for loop as shown above. Tip: You will need to create a running total and set it to zero before you start.