Loops & Lists

Tips for navigating the slides:
  • Press O or Escape for overview mode.
  • Visit this link for a nice printable version
  • Press the copy icon on the upper right of code blocks to copy the code

Loops

Why loops?

Consider the following code...


                    print(9 * 1)
                    print(9 * 2)
                    print(9 * 3)
                    print(9 * 4)
                    print(9 * 5)
                    

This code is repetitive and variable, but the variability is sequential - it just adds one to the right-hand side number each time. In English, we could describe this as "print out the first 5 multiples of 9".

We can simplify this code with a loop!

While loops

The while loop syntax:


                    while <condition>:
                        <statement>
                        <statement>
                    

As long as the condition is true, the statements below it are executed.


                    multiplier = 1
                    while multiplier <= 5:
                        print(9 * multiplier)
                        multiplier += 1
                    

The code is significantly shorter, and it can easily be extended to loop for more or less iterations.

Changing a while loop #1

You can change the initial values of the variables used in the condition:


                    multiplier = 3
                    while multiplier <= 5:
                        print(9 * multiplier)
                        multiplier += 1
                    
  • What will be the first thing displayed? 27
  • What will be the last thing displayed? 45
  • How many iterations? 3 (for values of 3, 4, 5)

Changing a while loop #2

You can change the condition:


                multiplier = 3
                while multiplier <= 10:
                    print(9 * multiplier)
                    multiplier += 1
                
  • What will be the first thing displayed? 27
  • What will be the last thing displayed? 90
  • How many iterations? 8 (for values of 3, 4, 5, 6, 7, 8, 9, 10)

Changing a while loop #3

You can change how much the values change between iterations:


            multiplier = 3
            while multiplier <= 10:
                print(9 * multiplier)
                multiplier += 2
            
  • What will be the first thing displayed? 27
  • What will be the last thing displayed? 81
  • How many iterations? 4 (for values of 3, 5, 7, 9)

Changing a while loop #4

You can change the computation inside the while loop:


            multiplier = 3
            while multiplier <= 10:
                print(10 * multiplier)
                multiplier += 2
            
  • What will be the first thing displayed? 30
  • What will be the last thing displayed? 90
  • How many iterations? 4 (for values of 3, 5, 7, 9)

Beware infinite loops

Uh oh..


            counter = 1
            while counter < 5:
                total += pow(2, counter)
            

What one line of code would fix this?
counter += 1

Lists

Lists

A list is a container that holds a sequence of related pieces of information.


The shortest list is an empty list, just 2 square brackets:


            members = []
            

Lists can hold any Python values, separated by commas:


            members = ["Pamela", "Tommy", "Amber"]

            ages_of_kids = [0, 2, 8]

            prices = [79.99, 49.99, 89.99]

            remixed = ["Pamela", 7, 79.99]
            

Accessing items (Bracket notation)

Each list item has an index, starting from 0.


            temps = [48.0, 30.5, 20.2, 99.0, 52.0]
            # Index:   0     1     2     3     4
            

Access each item by putting the index in brackets:


            temps[0]  # 48.0
            temps[1]  # 30.5
            temps[2]  # 20.2
            temps[3]  # 99.0
            temps[4]  # 52.0
            temps[5]  # 🚫 Error!
            

Negative indices are also possible:


            temps[-1]  # 52.0
            temps[-2]  # 99.0
            temps[-6]  # 🚫 Error!
            

List length

Use the global len() function to find the length of a list.


            attendees = ["Tammy", "Shonda", "Tina"]

            print(len(attendees))   #  3

            num_of_attendees = len(attendees)
            print(num_of_attendees)
            

🤔 What could go wrong with storing the length?

Modifying list items

Python lists are mutable, which means you can change the values stored in them.


Use bracket notation to modify single items in the list:


            temps = [48.0, 30.5, 20.2, 99.0, 52.0]
            temps[2] = 22.22
            temps[-1] = 55.55
            

What if we change the value of an item beyond the list length?


            temps[5] = 111.11 # 🚫 Error!
            

Looping through a list

You can use a standard while loop:


            scores = [80, 95, 78, 92]
            total = 0
            i = 0
            while i < len(scores):
                score = scores[i]
                total += score
                i += 1
            

😍 Python allows provides a for-in loop for lists:


            for score in scores:
                total += score