Python - For Loop

Python - For Loop

for, for loop, loop, nested loop, python, python for loop

The Python for loop is used to iterate a sequence. The for keyword acts very similarly to that of C++ and Java. Let's have a look at some for loop examples below.

For loop flowchart

Before we dive into code examples, let's take a quick look at the flowchart below. First we execute the body and then we check a condition. If it's true we continue, otherwise we exit. This is essentially how all other high level programming languages as well (String, List, Range, List, Tuple, Dictionary, etc). The only thing that changes for Python built in function is that we will be using the for in syntax. Let's have a closer look at some of the types of loops below.

Iterating over a string

We can use the for in syntax to iterate over the characters in a string. See the example below, let's assume that we want to print all of the letters in the word "strawberry". With only a few lines of code we are able to easily print every letter using the print command.

for x in "strawberry":
  print(x)
#Output
s
t
r
a
w
b
e
r
r
y


Iterating over a collection

Iterating over a collection in Python is very similar to iterating over the characters, string except well we are iterating objects now. In the code example below we are initializing an array of strings named fruits. This will print the name of each fruit in the string array. Notice the fruit are printed in the order by index. We have this for in code block on GitHub as well.

fruits = ["apricot""blueberry""strawberry"]
for x in fruits:
  print(x)
#Output
apricot
blueberry
strawberry


Using the break statement

When we are iterating, sometimes it may be required to break at a certain condition. Consider a scenario in which we have a list of fruit, but must stop execution once a blueberry is reached. We need to stop iterating when we reach a certain string value. Using the equality operator we check if the current string is equal to "blueberry". If it's is we'll break, otherwise we print the fruit name. This can be used in a variety of scenarios to bring control out of the for in execution.

fruits = ["apricot""blueberry""strawberry"]
for x in fruits:
  if x == "blueberry":
    break
  print(x)
#Output
apricot

 

Using the continue statement

Similar to a scenario where we want to break during iteration, we can also use a continue statement when a certain condition occurs. Consider the same example above, except instead of stopping when we reach "blueberry" we just want to skip over it. Check out the code example below.

fruits = ["apricot""blueberry""strawberry"]
for x in fruits:
  if x == "blueberry":
    continue
  print(x)
#Output
apricot
strawberry


Using the range() function

If you need to iterate through a specific range of values, you can use the range() function. Range() returns a sequence of numbers, you can pass it a single number whereas it starts at range 0, or pass it two values an specify a min and max for the range. The max parameter determines the number of times to execute the range() method.Let's look at this block of code below which shows how to iterate using a range given a min/max range. There is also an overload to pass the increment number, we will not show this but it is used in the same manner as shown below.

for x in range(26):
  print(x) #Output
3
4
5


Using the else statement

We can also specify an optional else clause to execute if the for condition is false. This allows us to specify code that will be executed when iteration is finished. Let's take the Range() function example from above and show what is possible when using the else part. Below we will display the text "I'm done!" in the else block after we finish executing all iterations.

for x in range(26):
  print(x)
else:
  print("I'm done!")
#Output
3
4
5
I'm done!


Working with nested for loops

Last but certainly not least we have the nested loops! Nested execution is great when we need to iterate multiple collections at the same time. Suppose we have two arrays, fruit colors and fruits. Now we want to print every combination of color and fruit from each array. Below we are assigning a color to each fruit, notice the order in which they are printed as the outer for index is iterated first. In the real world you may be mapping two data points together across large data sets. An example would be when updating attributes in a system where every item must be updated.

colors = ["red""blue""green"]
fruits = ["apple""banana""cherry"]

for x in colors:
  for y in fruits:
    print(x, y)
#Output
red apple
red banana
red cherry
blue apple
blue banana
blue cherry
green apple
green banana
green cherry


Back to The Programmer Blog