Previous Lesson Table of Contents Next Lesson

Suppose you want to print x, where x is the letter a, you would write:

print(x)

But what happens if you wanted to print the first ten letters? As far as we know, we would have to write the following:

print("a")
print("b")
print("c")
...
print("j")

That’s a lot of print statements! Something even as trivial as this can become quite monotonous and error prone. We can make this more compact using a for loop:

for x in ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]:
    print(x)

This will do the same thing as the previous code block, but it’s only two lines! In more descriptive terms, what we are saying is this: for each value of x, print it out. For each iteration of the loop, we assign x to the next letter in our list and print it out.

Note that this syntax is valid for any collection, so in addition to list, we could also iterate over a set, tuple, or str. The syntax is just:

for variable in collection:
    perform_action_with_variable(variable)

It should be noted that the code we want to execute for each iteration of our loop must be tabbed in at least once so that Python will know.

In conclusion, if you are ever writing the same code over and over again for various inputs, consider using a for loop. We’ll stop for now and practice what we have learned:

  • Create a for loop to iterate over the numbers 1 through 5, and for each value, print out its value, and then print out its value added with 1. (solution)

  • Create a for loop to iterate over the numbers 1 through 10, and for each value, print out its value, and then append that value multiplied by 2 to an (initially) empty list l. (solution)

  • Challenge: how would you use for loops to iterate through all possible pairs in the following tuple: ("a", "b", "c")? (solution)

If you feel that you have mastered for loops, feel free to move on to while loops!