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!')

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

The for Loop

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 a previous lesson we learned about lists which are naturally sequences but that’s not the first sequence type you have learned. The next table shows example for loops using types that we’ve learned already.

Type

Sequence of

str

Characters in the string

File handle

Lines in the file

list

Items in the list

dict

Keys in the dictionary

Here are some examples:

A String is a Sequence of Letters

A for loop over a string runs once per letter in the string:

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

A File Handle is a Sequence of Lines

A for loop over a file handle runs once per line in the file:

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

A List is a Sequence of Items

A for loop over a list runs once per list item:

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

A Dictionary is a Sequence of Keys

A for loop over a dictionary runs once per key:

animals = { 'Lion': 'Panthera Leo',
           'Tiger': 'Panthera Tigris',
           'Bear': 'Ursus Arctos',
          }
for key in animals:
    print(key)
print('Oh my!')

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