For Loops 3 Lists - Lakelands Computing

Title
Go to content
For Loops part 3 - Looping over  / through Lists
Looping through lists works in much the same way as looping through a string. It treats each item in the list as one loop.

  • names = ["Alice", "Bob","Claire","Dave"]

  • for x in names:
    • print ("Welcome")

This would print "Welcome" four times, one for each person in the names list. In the example I used for x in names, but you can (and often should) use something more informative than x for example:

  • for person in names:
    • print ("Hello", person)

This would print "Hello" and the persons name for each person in the list, eg Hello Alice, Hello Bob etc

You can also use for Loops to perform calculations, Lets take a list of numbers, say you wanted to know how many boxes you had in total but the were stacked up in different piles:

  • boxes = [1,3,5,3,6,7,7,3,2]
  • boxCount = 0

  • for item in boxes:
    • boxCount = boxCount + item.
    • print ("running total is :",boxCount)

  • print ("Final total is :",boxCount)

 
Where For Loops and lists can be very useful is searching within 2D lists. Take a look at the example in the trinket. Notice how after it has asked the person what they want and stored their answer in the selected variable it loops through the menu list, and compares the first part of each item - item[0](in the menu list) to the selection. When it finds a match it prints our the second part of the item item[1] - the price.

What it is actually doing is looping through the main list. Each item in the main list is a sub list containing the product and the price. The if statement checks if the first part - item[0] i.e. the product - matches the selection (which is stored in selected). If it does then the program print out the second part - item[1] - the price. If they don't match the for loop moves onto the next item in the main menu and starts the if statement again.
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content