Skip to content

Python For Loop Tutorial – All You Need to Know!

Python For Loop Tutorial Cover Image

The Python for loop is an incredibly useful part of every programmer’s and data scientist’s tool belt! In short, for loops in Python allow us to repeatedly execute some piece (or pieces) of code. Similarly, we can use Python for loops to iterate over a sequence of items (such as a list, tuple, or string) or any other iterable object.

Being able to understand and use for loops allows you to become a much stronger programmer. Remember, programming is based around the DRY (don’t repeat yourself) principle. Because of this, being able to repeat an action multiple times allows you to write simple, concise code.

Python For Loop – Video Tutorial

Why Do We Need Python For Loops?

Python for loops allow us to repeatedly run some code, allowing us to make our code much more concise and readable. For example, imagine you wanted to print a 'Hello!' to your users five times. We could write the following code:

# Greeting someone multiple times
print('Hello!')
print('Hello!')
print('Hello!')
print('Hello!')
print('Hello!')

Oof! that’s more code than we were hoping. Imagine we wanted to change the greeting now – we’d have to make the change on every single line!

This is an example where for loops can be incredibly helpful. Let’s take a look at how we can combine the for loop with the Python range() function to complete a task a certain number of times:

for iteration in range(5):
    print('Hello!')

You’ll learn more about the Python range() function later in this tutorial, but for now just know that it creates a sequence that is a certain number of items long – in this case five.

See how much simpler that is! We immediately know how many times the action is being repeated without having to count the number of lines. We can, similarly, modify the greeting by only changing it once, rather than multiple times.

Let’s now take a look at how Python for loops are actually written!

Python For Loops Syntax

Let’s begin by exploring what the syntax for a for loop looks like in Python:

for item in sequence:
     expression

Let’s break this down a little bit:

  • For loops start with the keyword for, indicating the we want to repeat an action for a certain number of times
  • The keyword in indicates that we want to repeat an action in a particular sequence
  • The expression (or expressions) are written on an indented line, following a colon
Python For Loop Syntax
How Python for loops work

Python For Loop Example: Iterating over a List

Let’s take a look at an example. We know that lists are sequence objects that contain data. Let’s say you’re given a list of names and want to print out every name that appears in that list. We could, of course simply index the list’s items and print them out.

Let’s see what this might look like:

# Printing out list items using the list indices
names = ['Kate', 'Nik', 'Evan', 'Kyra']
print(names[0])
print(names[1])
print(names[2])
print(names[3])

# Returns:
# Kate
# Nik
# Evan
# Kyra

While this approach works, it’s not very convenient. We need to:

  • Know how many items exist in the list
  • Repeat a code multiple times

Imagine if the list had hundreds of items! Let’s now see how we can convert this code into a for loop.

# Printing out list items using a for loop
names = ['Kate', 'Nik', 'Evan', 'Kyra']
for name in names:
    print(name)

# Returns:
# Kate
# Nik
# Evan
# Kyra

Let’s break this down a little bit:

  • The code was set to run for each item (our name) in our sequence (names)
  • The loop ran an expression (printing our name)

It continued this process until the end of the list was reached. For this reason, for-loops in Python are considered definite iteration.

You may be wondering how Python knew that each item in our list names was a name. The truth is, it didn’t! We could have named the sequencer anything that we wanted to name this sequencer anything that we wanted.

You could also have written:

names = ['Kate', 'Nik', 'Evan', 'Kyra']
for potato in names:
    print(potato)

# Returns:
# Kate
# Nik
# Evan
# Kyra

As long as you use the same name for your item in your statement, your for-loop will run!

Python strives for readability. Because of this, it makes sense to make it clear to your readers what you are trying to accomplish with your code!

How Do For Loops Work?

Before we dive further into Python for loops, let’s take a moment to explore what is meant by loops in the first place. We mentioned earlier that loops allow us to iterate over a set of items and execute a statement. What this means, is that for each item in a sequence (say, a list), we can execute a statement.

This is easily explained with a flow diagram:

Flow Diagram for Python For Loops

The above diagram displays the flow of the Python For Loop:

  1. We grab the first item, and execute an expression on it.
  2. We return to the sequence and check if another item exists.
  3. If there is another item, we execute another expression.
  4. Otherwise, we end the loop and exit.

Let’s now go into more detail about how the Python range() function is often used to extend for loop functionality.

Extending Python For Loops with the Range() Function

If you want to loop through a particular code a certain number of times, you can use the range() function to make this much easier.

The Python range() function creates a sequence of numbers. These numbers generally start at 0 and generally increment by 1. Let’s take a look at what the function looks like:

# Understanding the Python range() Function
range(start, end, step)

Let’s break this down a little bit:

  • The range() function returns a list-like object containing a sequence of numbers
  • The start parameter indicates what number to start at and defaults at 0 and is optional
  • The end parameter indicates what number to go up to (but not include). This parameter is required.
  • The step parameter indicates to increment numbers and defaults to 1. The value can be positive or negative and is optional.

Now, let’s see how we might complete an expression five times without the use of the range() function. We could create a list that has five items and we could write the following:

# Executing an expression five times without the range() function
sequence = [0,1,2,3,4]
for number in sequence:
    print('Learn Python with datagy.io')

# Returns:
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io

This was straightforward because we only wanted to repeat something five times. However, say we wanted to loop over something a hundred times? A thousand times? This is where the range() function comes in handy.

Let’s take a look at our example again, and re-write it by using the range() function:

# Executing an expression five times with the range() function
for number in range(5):
    print('Learn Python with datagy.io')

# Returns:
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io

This returns the exact same thing but is much easier to write and control. We know exactly how often this code will be executed.

A Note On For Loop Styles

You may note that in the above for loop, we didn’t actually access the item inside the sequence. Because of this, it’s convention to make this clear to the reader that the for loop is used only for repeating something multiple times.

Since we don’t actually make use of the number iterator in our example above, we should make this clear by changing it to an underscore _.

Let’s rewrite this for loop with this stylistic note:

for _ in range(5):
    print('Learn Python with datagy.io')

# Returns:
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io
# Learn Python with datagy.io

This accomplishes the same thing but it’s clearer to any future reader of your code that the value isn’t being used in the expression.

If Statements in Python For Loops

We can further extend the capabilities of our for loops by adding condition if-else statements. This allows us to execute an expression only if a condition is met. Furthermore, if a condition isn’t met, then we can have our loop either do nothing or do something else entirely!

Let’s see how we can implement a conditional if-else in our for loop:

for item in sequence:
    if condition:
        ...
    else:
        ...

Let’s break down what we did here a little bit:

  1. We wrote our for loop as we normally do
  2. We embedded an if-else statement in our code
  3. If a condition is met, then Python moves to the first indent
  4. If it isn’t met then the other expression runs

Writing a ... following either a function declaration or an if-else statement is an easy way to add placeholders to your text. This is the same as writing pass, but perhaps a bit clearer as a placeholder. It can be a signal to you that you need to add additional code there. If left there, nothing will execute.

Now let’s take a look at an example:

Example: Adding a Condition to a Python For Loop

For our example, let’s take a look at how we can loop over a range() function object that contains the values from 0 through 10 and only print out the multiples of 3. We can use the modulus operator to calculate whether a value is a multiple of another value. Toggle the section below to learn more:

The Python modulus (%) operator returns the remainder from a division. This means that if we write the expression 3 % 2, the value 1 would be returned. This is because 2 goes into 3 once, leaving a remainder of 1.

We can use this operator to see if a number is a multiple of another number by evaluating whether the value returned through the modulus operation is equal to 0. If a number is a multiple, then the remainder will always be zero.

For example, we could write: print(51 % 3 == 0). This code would print the value True. Because of this we can know that 51 is a multiple of 3.

Let’s see how we can write our for loop to print out only multiples of 3:

for number in range(11):
    if number % 3 == 0:
        print(number)
    else:
        pass

# Returns:
# 0
# 3
# 6
# 9

Now, since our else statement doesn’t actually accomplish anything, we can actually omit it. If no else is provided, Python implicitly passes any cases that would fit into that category:

for number in range(11):
    if number % 3 == 0:
        print(number)

# Returns:
# 0
# 3
# 6
# 9

This is a bit more concise and, perhaps, easier to read.

The Nested Python For Loop

We can even nest a for loop inside of another for loop. This can be helpful when you are, say, iterating over a list of lists and want to extract or manipulate items.

By nesting a for loop, we create two (or more) layers of iteration. We have the outer for loop (which is called first) and the inner for loop (which is called inside the outer for loop). Let’s see what the basic syntax looks like:

for item in sequence:
    for subitem in subsequence:
        ...

When we nest for loops, it’s important to note that the first iteration of the entire inner loop happens before the next item in the outer loop is completed.

Let’s take a look at an example to help clarify this:

# An example of a nested for loop
for item in [1, 2]:
    print(item)
    for subitem in ['a', 'b', 'c']:
        print(subitem)

# Returns:
# 1
# a
# b
# c
# 2
# a
# b
# c

We can see that Python doesn’t move onto the second item in our outer loop until all the iterations of the inner look have been completed!

Example: Iterating Over Lists of Lists with Nested For Loops

Let’s take a look at an example of how you may want to use nested for loops in Python. One useful application is to be able to iterate over subitems in lists of lists.

Normally, when we have a list of lists and we iterate over the outer list, only the inner lists are returned:

nested = [['welcome', 'to', 'datagy'], ['we', 'are', 'happy'], ['you', 'are', 'here']]
for item in nested:
    print(item)

# Returns:
# ['welcome', 'to', 'datagy']
# ['we', 'are', 'happy']
# ['you', 'are', 'here']

Since each item in our outer list is also an iterable object, we can actually loop over each item in that list using a nested for loop!

nested_list = [['welcome', 'to', 'datagy'], ['we', 'are', 'happy'], ['you', 'are', 'here']]
for nest in nested_list:
   for item in nest:
      print(item)

# Returns:
# welcome
# to
# datagy
# we
# are
# happy
# you
# are
# here

Knowing how to work with nested loops can give you much greater flexibility and control over how your code runs. Be sure to be mindful of how you name your variables in order to make your code readable.

The Break Statement in Python For Loops

In this final section, you’ll learn how to interrupt the flow of a Python for loop using the break keyword. The break keyword is used to, well, break a flow and cause iteration to end. This can be helpful if you only want to reach a given point in your code, without knowing where it is.

When you’re working with large sequences, this can help save time and memory of your program and allow your programs to execute significantly faster.

Let’s take a look at how we can integrate the break keyword into a for loop. We will evaluate each item for a particular condition. If the condition is met, then we will break the for loop. At this point, the whole loop stops and no further code in that loop is executed:

# Breaking the flow of Python For Loops
names = ['Kate', 'Mel', 'Adam', 'Nik', 'John']
for name in names:
    if name == 'Nik':
        break
    print(name)

# Returns:
# Kate
# Mel
# Adam

We can see that once the condition of name == 'Nik' becomes True, the break statement is passed and the for-loop ends! Because of this, Nik and John are not printed.

Conclusion and Recap

In this post, we covered everything you need to know about the Python For Loop. We started off with an understanding of the syntax used and how the flow actually works within Python. We then also explored how to expand on for loops using the Range() function, using else statements, and using nested for loops.

Below, you’ll find a quick recap of Python for loops:

  • Python for loops allow us to iterate over a sequence to execute some expression of code
  • Because the number of times they iterate is defined at the beginning, they are known as forms of definite iteration
  • They allow us to simplify and streamline our code when we execute a similar line of code multiple times
  • They can be combined with the range() function to complete a task a given number of times
  • They can be nested to iterate within iterations
  • We can control their behaviour using if-else statements
  • We can terminate their flow by using the break keyword

Additional Resources

Check out these related tutorials to learn more:

Leave a Reply

Your email address will not be published.