Python For Loop Tutorial – All You Need to Know!

Python For Loops 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 iterate over a set of items multiple times and execute an expression (such as a function).

But what do we mean by a set of items? This can include items lists, strings, sets, tuples, or dictionaries.

Python For Loop – Video Tutorial

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 explain this in a way that’s a lot less technical.

As an example, imagine you’ve been given a list that contains names. You’ve been asked to write a script that prints out each of the names.

Python For Loop Syntax

Let’s see what this looks like without a for-loop:

names = ['Nik', 'Sam', 'Jane']
print(names[0])
print(names[1])
print(names[2])

# This prints out:
# Nik
# Sam
# Jane

This is an ok approach because the list only contains three items. But imagine if the list had hundreds of items! This is where for-loops are incredibly useful.

Let’s see how to write this as a for-loop:

names = ['Nik', 'Sam', 'Jane']

for name in names:
   print(name)

This will return:

Nik
Sam
Jane

The for-loop iterated over each item (name) in the provided list (names) and executed our statement (print(name)) for each item (name).

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

Now you may be wondering how Python knew that we were referring to names? The truth is – it didn’t! We could have named the item whatever we wanted.

You could also have written:

for potato in names:
   print(potato)

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!

Are you enjoying our content? Consider following us on social media! Follow us on LinkedIn, Twitter, or Instagram!

What Are Loops?

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.

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.

Say we wanted to iterate over something five times. We could create a list that has five items and we could write the following:

list_five = [0,1,2,3,4]
for number in list_five:
     print(list_five[number], "Welcome to datagy.io!")

This would return the following:

0 Welcome to datagy.io!
1 Welcome to datagy.io!
2 Welcome to datagy.io!
3 Welcome to datagy.io!
4 Welcome to 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? Writing out a list by hand would annoying and time-consuming! Python makes this easy by using the Range() function. The Range() function returns a range object, which is an iterable sequence of integers.

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

for number in range(5):
    print(number, "Welcome to datagy.io!")

Just like before, this returns:

0 Welcome to datagy.io!
1 Welcome to datagy.io!
2 Welcome to datagy.io!
3 Welcome to datagy.io!
4 Welcome to datagy.io!

Want to learn more Python? Check out our other Python posts, such as Understanding Functions in Python or our Python SQLite Tutorial. More posts are available in our Python archives!

A Quick Deeper Look at the Range() Function

The Range() function has only a single required parameter, but actually takes three parameters in total:

range(start, stop, step_size)

Let’s break this down a little:

  • By default, start will be set to 0.
  • Stop is the required parameter, which tells Python where to stop.
  • Step_size is the increment by which to increase.

When we wrote:

range(5)

Python interpreted this as:

range(0, 5, 1)

Which returned the numbers from 0-4, as the end parameter is not included.

Python For Loops and Strings

Strings are iterable objects in Python and can be looped over with a for-loop.

Each character is its own item and can be looped over. Let’s see what this looks like with an example:

for letter in "datagy":
    print(letter)

This would print out:

d
a
t
a
g
y

If Statements in Python For Loops

You can also combined for loops with if statements to make them run based on a condition.

To accomplish this, simply include the if statement in the indented block.

For example, if you wanted to get all multiples of 3 between 0 and 20, you could write a for loop with an if statement included.

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

This returns:

0
3
6
9
12
15
18

This allows you to greatly extend your for loops!

Want to learn everything you need to get started in Python for Data Science? Check out eBook!

The Nested Python For Loop

We can also nest a Python For Loop in another for loop! What happens when we nest a for loop within another for loop is that it will execute one item from the outer loop and then execute all items in the inner loop, then move onto the next outer item and repeat the inner loop again. This is more easily explained with an example:

numbers = [1,2,3]
words = ['data', 'science']
for number in numbers:
    print(number)
    for word in words:
        print(word)

Running this nested Python For Loop will return:

1
data
science
2
data
science
3
data
science

Why would we want to do this? The example above doesn’t really illustrate a useful example. But, say we had a list of lists and wanted to print all the items, we could accomplish this with a nested Python for loop:

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

Executing this code would print out the following:

welcome
to
datagy
we
are
happy
you
are
here

The Else Clause in the Python For Loop

Adding an Else Statement to a Python For Loop has a particular purpose: it executes when the for loop has run out of iterables, or is interrupted. Let’s explore this with another example:

welcome = ['Welcome', 'to', 'datagy']
for word in welcome:
   print(word)
else:
   print("You're great!")

This returns the following:

Welcome
to
datagy
You're great!

The Break Statement in the Python For Loop

The break statement can be used if you want to interrupt your for-loop when a certain condition is reached.

Let’s look at another example: you’re given a list of names and want to print all the names until the name “Nik” is reached. To accomplish this, you can write:

names = ['Jane', 'Mel', 'Adam', 'Nik', 'John']
for name in names:
    if name == 'Nik':
        break
    print(name)

This prints out:

Jane
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: Python For Loop Tutorial

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 – finally- using nested for loops.

Thanks for reading the whole tutorial! If you enjoyed it, please consider sharing it with your friends, coworkers, or others!

Introduction to Python for Data Science

Did we mention we recently released an eBook? Introduction to Python for Data Science takes you through the whole journey of getting started with Python for Data Science. Click the button below to find out out more or buy it directly:

Cover Image for Introduction to Python for Data Science