The for Loop

In this lesson I introduce simple syntax with powerful applications. Earlier, you learned how to create and maniuplate lists. What if you wanted to run some code for each item in a list? To do that you need a for loop. Here’s an example:

animals = ['Lions', 'Tigers', 'Bears']
for item in animals:
    print(item)
print('Oh my!')

Notice that there’s a list animals. The print statement inside of the the for loop is executed once for each element in the animals list. Enter it into the next cell:

[ ]:

Again, notice:

  • The print() statement inside the for loop is run once for each item in the list

  • The items in the list are assigned to the variable item one by one

This image shows the important parts of the for loop:

Image of a for loop

The most powerful thing about Python’s for loops is the idea that a sequence goes on the right of the in keyword.

Sequences

A sequence is anything that can be stepped through one element at a time. In Python many data types can be treated like sequences. In the last lesson we learned about lists which are naturally sequences but that’s not the first sequence type you have learned. Here are some examples:

Strings are a sequence of letters:

sentence = "Mary had a little lamb."
for letter in sentence:
    print(letter)

File handles are a sequence of lines:

file_handle = open('files/example.txt')
for line in file_handle:
    print(line.strip())
file_handle.close()

Try the example for loops in the next cell:

[ ]:

Numerical Sequences

If you’ve programmed in another language you’ve probably seen the C-style for loop. If not, no big deal! In many other languages the for loop is for counting numbers and the syntax enables you to make numerical sequences (e.g. 0, 1, 2, …) but not “step through” things easily. Counting numbers is important sometimes and Python gives you a way to do that. For example:

for number in range(10):
    print(number)

Try it in the next cell:

[ ]:

What numbers does the list produce?

The range function can produce more complicated sequences. If you give range two numbers it starts at the first and ends one before the second. For example:

for number in range(5, 10):
    print(number)

Try changing the previous cell to the two-argument version of range.

Loop Variables

Here’s a pop quiz! What is the difference between the output of these three for loops:

for item in animals:
    print(item)

for animal in animals:
    print(animal)

for duck in animals:
    print(duck)

Not sure? Try them out:

[ ]:

Answer: NOTHING! The difference in the for loops is the name of the loop variable. There is nothing special about the name of the loop variable, it’s simply a variable that the for loop creates for you to hold individual items. It’s up to you to choose a name that suits your program. It’s best to chose a name that will help you understand what’s in the variable. Here’s a better question:

What is the most appropriate variable name from the loops above?

  1. item

  2. animal

  3. duck

Algorithms With for

The for loop has simple syntax with powerful implications. If you’re learning to program for the first time it’s important for you to be able to step through the for loop one iteration at a time as a way to understand what it does. The debugger is really great for this! Here’s an example with each iteration of the loop spelled out in a table:

This for loops calculates the sum of every number in a list:

numbers = [1, 23, 46, 92, 9, 12, 5]
total = 0
for number in numbers:
    total = total + number
print(total)

Let’s look at the value of number and total step-by-step:

Step #

number

total

0

0

1

1

1

2

23

24

3

46

70

4

92

162

5

9

171

6

12

183

7

5

188

Now enter the code and confirm those steps in the debugger:

[ ]:

Modify the List

The loop variable is a copy of the list element so changes in the loop variable do not affect the contents of the list. Here’s an example for loop the changes the list by doubling each element in the list:

numbers = [1, 23, 46, 92, 9, 12, 5]
for index in range(len(numbers)):
    numbers[index] = numbers[index] * 2
print(numbers)

Notice the following:

  1. The loop uses range to get numbers.

  2. range is given len(numbers), the length of the list as an argument.

  3. Inside the for loop I use the index variable to get elements of the list.

Simulating the loop in a table we get:

Step #

index

numbers[index] before -> after

1

0

1 -> 2

2

1

23 -> 46

3

23

46 -> 92

4

46

92 -> 184

5

92

9 -> 18

6

9

12 -> 24

7

12

5 -> 10

Enter the for loop example and confirm these steps in the debugger:

[ ]:

Filtering

Any legal Python statement can be inside of a for loop. Importantly you can make a decision inside of a for loop that filters elements. Here’s an example of an algorithm that prints some elements in the list but not others:

numbers = [1, 23, 46, 92, 9, 12, 5]
for number in numbers:
    if number < 20:
        print(number)

Notice that the if is inside the for. Simulating the loop in a table gives us:

Step #

number

number < 20

Action

1

1

True

print

2

23

False

3

46

False

4

92

False

5

9

True

print

6

12

True

print

7

5

True

print

Now enter the example and use the debugger to confirm the table:

[ ]:

Searching the List

Sometimes you want to find something in the list. Of course, this is conveniently done with the in operator in Python but there are more complicated cases that require a for loop. An algorithm that searches a sequence shold stop when it has found what it’s looking for. The break statement stops a for loop from executing, leaving any remaining items untouched. Here’s an algorithm that searches for a number in the list:

numbers = [1, 23, 46, 92, 9, 12, 5]
for number in numbers:
    if number == 92:
        print("I found it!")
        break

Running break stops the loop early. Here’s a simulation:

Step #

number

number == 92

Action

1

1

False

2

23

False

3

46

False

4

92

True

Print and break

Enter the example and confirm the simulation in the debugger:

[ ]:

Note: Programming Style

The break statement is controversial. Some people discourage its use because they believe that it makes code less readable, or harder to simulate in your head. As you gain experience you’ll be able to judge for yourself how readable and clear code is. Every statement has a time and a place.

What about a function that does the same thing as ``in``? Let’s move our filter code into a function called find_in. The function returns True if the item is in the list and False otherwise.

  • Name: find_in

  • Arguments:

    • number (integer) - The number to search for.

    • items (list of integer) - The list to search in.

  • Returns: (bool) True if number is found in items otherwise False.

Here’s the function:

def find_in(number, items):
    for item in items:
        if item == number:
            return True
    return False

Here’s how to call the function on our list:

numbers = [1, 23, 46, 92, 9, 12, 5]
if find_in(92, numbers):
    print("I found it!")

Enter the function and corresponding call into the next cell:

[ ]:

Follow the execution in the debugger. What happens if you search for a number that’s not in the list?