Home

 › 

Articles

 › 

For Loop In Python: What You Need To Know, With Examples

Ruby Vs. Python

For Loop In Python: What You Need To Know, With Examples

Loops are crucial statements that are used in many programming languages. When we want to repeat a set of instructions over a selection of elements, loops help us to do this effectively. Being able to perform operations for a specific set of elements or until a specific outcome is reached allows task automation and an efficient workflow. In this article, we’re going to give a brief overview of for loops in Python, how they work, and how they’re used.

What Are For Loops in Python?

There are 3 main types of loops in Python – while loops, for loops, and nested loops. While loops are used to repeat an operation while a condition is true and stop once the condition is false. Loops inside other loops are known as nested loops. For loops, however, execute code several times over a specific element sequence.

How Are For Loops in Python Used?

As previously mentioned, for loops are used to execute code repeatedly for a list of elements. This repeating is known as iteration. The basic syntax for a for loop is as follows:

for [element] in [sequence]:
      [code to be executed]
     [function to be executed]

for example, we can have a for loop that prints each element in a list of vegetables. This would be designated as such:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)

The for loop will iterate over each element, with the variable “vegetable” taking the value of the elements. Each element is printed to the console as can be seen in the image.

Illustration of the basic syntax of a for loop.

Using For Loops With an Else Statement

An “else” statement is an optional statement within a for loop, that is executed once the for loop terminates. Let’s take a look at this code to illustrate:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)
else:
    print("All vegetables have been printed.")

In this modified example, we’ve included a simple else statement that prints a message once all the vegetables have been printed. This can be seen in the image below.

A for loop with an else statement, with its output.

Using For Loops With an if Statement

Another common statement to use with for loops in Python is the “if” statement. This is used to check whether a certain condition is true, and then modify the result. We can see this in this code block:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)
    if vegetable == "tomato":
        print("Encountered a tomato!")
else:
    print("All vegetables have been printed.")
)

We’ve used an if statement to print an additional message if the “tomato” element is encountered. It is, so the output is changed, as can be seen below.

Illustration of a for loop with an if statement.

Using For Loops With the Range() Function

Another way to use for loops is to include the range() function. This can be used to iterate over specific elements when we don’t want to traverse every single element. The modified code to show this is as follows:

vegetables = ["cucumber", "tomato", "potato", "carrot", "spinach"]

for i in range(1, len(vegetables), 2):
    print(vegetables[i])
else:
    print("Printing every other vegetable is complete.")

Here, we’ve used the len() function to determine the list length, and the range() function to operate on every other element. Therefore, only “tomato” and “carrot” are printed, as can be seen in the image.

A for loop with the range() function implemented.

What Control Statements Are Used With For Loops in Python?

3 kinds of control statements can be used with for loops in Python. These work to adjust the execution of the loop. These statements can be continue, break and pass statements. A quick look at these follows.

Continue statements

These are used to pause the execution of a loop and continue to the next operation. We can use similar code to illustrate this:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    if vegetable == "tomato":
        continue
    print(vegetable)
else:
    print("All vegetables have been printed.")

By including a continue statement, we’ve modified the output as we can see in the image. The “tomato” element hasn’t been printed, since the continue statement indicates that, once we reach this element, it’s skipped over. The for loop then continues with the rest of the elements. The else statement prints the other elements as before.

A continue statement illustrated.

Break statements

This type of statement is used to terminate or “break” a for loop in Python, even if it’s not finished executing. The next statement after the loop is then picked up by the program. We can use the same vegetable example to show this. Have a look at this code:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    if vegetable == "tomato":
        break
    print(vegetable)
else:
    print("All vegetables have been printed.")

We use an if statement as before, but also a break statement. Once the “tomato” element is found, the for loop is broken, so that only the first element is printed. We can see this in the output.

A for loop with a break statement.

Pass statements

The third kind of control statement is known as a pass statement. A pass statement doesn’t actually do anything, so it’s mostly used as a placeholder to maintain the intended structure of the code. Often, it’s replaced later with a function or otherwise executable code. For example, take this code:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    print(vegetable)
    if vegetable == "tomato":
        pass
else:
    print("All vegetables have been printed.")

A pass statement is included here, but doesn’t actually affect the output of the code.

A pass statement included in a for loop.

A note on nested loops

Nested loops don’t necessarily involve for loops, but often do. Any kind of loop can be placed inside another loop, where we require multiple levels of operation. The nested loop will iterate over each iteration of the loop it’s within, known as the outer loop. Let’s show this with the following example:

vegetables = ["cucumber", "tomato", "potato"]

for vegetable in vegetables:
    for letter in vegetable:
        print(letter)
    print("End of", vegetable)
else:
    print("All vegetables have been printed.")

We’ve modified this to include a second for loop within the first. When each vegetable element is encountered, we print each letter in the name, followed by “End of [vegetable]”. We can see the changed output in the image.

A second loop can be nested within the first loop.

For Loop in Python: Wrapping Up

To conclude, for loops are a relatively simple yet extremely important construct in Python, allowing you to execute refined and repetitive operations efficiently. They can be used to iterate over lists of elements, whether they’re character strings or numerical. Each element can be operated on individually, and for loops can be nested within each other to perform additional operations as required. Control statements are also often used to manage operations based on specific conditions.

Frequently Asked Questions

What is a for loop?

A for loop is used to traverse a list of elements and perform an operation on each one, allowing you to execute repetitive operations with some degree of automation.

What programming languages use for loops?

As well as in Python, for loops are used in Java, C, C++, JavaScript, PHP, Swift and Ruby, among others.

What are the rules for using for loops?

It’s best to avoid modifying elements while a for loop is executing, because this can lead to unpredictable behavior. If you want to do this, it’s recommended to make a copy of the list.

What statements can be used with for loops?

You can use else, if, break, pass and continue statements to modify the behavior of a for loop.

Can you have more than one for loop?

Yes, you can use more than one for loop. An additional loop is often nested within the outer loop, providing further operations on each iteration of the outer loop.

How does a while loop differ to a for loop?

A for loop is used to iterate over a sequence of elements, executing some code for each element. However, a while loop is used to execute a code block while a condition is true.

To top