Back to articles list Articles
9 minutes read

How to Write a For Loop in Python

The for loop is one of the basic tools in Python. You will likely encounter them at the very beginning of your Python journey. In this article, I’ll give you a brief overview of the for loop in Python and demonstrate with examples how you can use it to iterate over different types of sequences.

What Is a For Loop in Python?

Python is a powerful programming language that can be used for just about anything, and the for loop is one of its fundamental tools. You should understand it well and master it to build applications in Python.

A for loop allows you to iterate over a sequence that can be either a list, a tuple, a set, a dictionary, or a string. You use it if you need to execute the same code for each item of a sequence.

To explain the syntax of the for loop, we’ll start with a very basic example. Let’s say we want to keep track of the home countries of our students. So, we have the list new_students_countries, which contains the countries of origin for our three new students.

We use the for loop to access each country in the list and print it:

new_students_countries = ['Great Britain', 'Germany', 'Italy']
for country in new_students_countries:
    print(country)
	
Output:
Great Britain
Germany
Italy

Here, for each country in the list new_students_countries, we execute the print() command. As a result, we get the name of each country printed out in the output.

Let’s go over the syntax of the for loop:

  1. It starts with the for keyword, followed by a value name that we assign to the item of the sequence (country in this case).
  2. Then, the in keyword is followed by the name of the sequence that we want to iterate.
  3. The initializer section ends with “:”.
  4. The body of the loop is indented and includes the code that we want to execute for each item of the sequence.

Practice writing for loops with the course Python Basics. Part 1. It has 95 interactive exercises that cover basic Python topics, including loops.

Now that we’re familiar with the syntax, let’s move on to an example where the usefulness of the for loop is more apparent.

We continue with our example. We have the list new_students_countries with the home countries of the new students. We now also have the list students_countries with the home countries of the existing students. We will use the for loop to check each country in new_students_countries to see if we already have students from the same country:

students_countries = ['Belgium', 'Czech Republic', 'France', 
                      'Germany', 'Hungary', 'Ireland',
'Netherlands', 'Spain']
new_countries = 0
for country in new_students_countries:
    if country not in students_countries:
        new_countries += 1
print('We have students from', new_countries, 'new countries.')

Output:
We have students from 2 new countries.

As you can see, we start by initializing the variable new_countries with 0 value. Then, we iterate over the list new_students_countries, and check for each country in this list if it is in the list students_countries. If it is not, it is a new country for us, and we increase new_countries by 1.

Since there are three items in new_students_countries, the for loop runs three times. We find that we already have students from Germany, while Great Britain and Italy are new countries for our student community.

For Loops to Iterate Over Different Sequence Types

For Loops and Sets

As mentioned before, for loops also work with sets. Actually, sets can be an even better fit for our previous example; if we have several new students from the same new country, we don’t want them to be counted multiple times as if we have more new countries than we actually have.

So, let’s consider the set new_students_countries with the countries for four new students, two of whom come from Italy. Except for replacing a list with a set, we can use the same code as the above:

new_students_countries = {'Great Britain', 'Germany', 'Italy', 
'Italy'}
new_countries = 0
for country in new_students_countries:
    if country not in students_countries:
        new_countries += 1
print('We have students from', new_countries, 'new countries.')

Output:
We have students from 2 new countries.

Because we use a set instead of a list, we have correctly counted that only two new countries are added to our student community, even though we have three students coming from new countries.

For Loops and Tuples

We may also iterate over a tuple with the for loop. For example, if we have a tuple with the names of the new students, we can use the following code to ask the home country of each student:

new_students = ('James Bond', 'Adele Schmidt', 'Leonardo Ferrari')
for name in new_students:
    print('Where does', name, 'come from?')
	
Output:
Where does James Bond come from?
Where does Adele Schmidt come from?
Where does Leonardo Ferrari come from?

For Loops and Dictionaries

Now, we can iterate over a dictionary to answer the above question for each new student:
new_students_countries_dict = {'James Bond': 'Great Britain', 
                               'Adele Schmidt': 'Germany', 
                               'Leonardo Ferrari': 'Italy'}
for key, value in new_students_countries_dict.items():
    print(key, ' is from ', value, '.', sep = '')
	
Output:
James Bond is from Great Britain.
Adele Schmidt is from Germany.
Leonardo Ferrari is from Italy.

There are many different ways to iterate over a dictionary; it is a topic for a separate discussion by itself. In this example, I iterate through the dictionary items, each of which are basically tuples. So, I specify in the loop header to unpack these tuples into key and value. This gives me access to both dictionary keys and dictionary values in the body of the loop.

If you want to refresh your knowledge about dictionaries and other data structures, consider joining our course Python Data Structures in Practice.

For Loops and Strings

While iterating over sequences like lists, sets, tuples, and dictionaries sounds like a trivial assignment, it is often very exciting for Python beginners to learn that strings are also sequences, and hence, can also be iterated over by using a for loop.

Let’s see an example of when you may need to iterate over a string.

We need each new student to create a password for his or her student account. Let’s say we have a requirement that at least one character in the password must be uppercase. We may use the for loop to iterate over all of the characters in a password to check if the requirement is met:

uppercase = False
password = "i@mHappy"
for char in password:
    if char.isupper():
        uppercase = True
print(uppercase)

Output:
True

Here, we initialize the variable uppercase as False. Then, we iterate over every character (char) of the string password to check if it is uppercase. If the condition is met, we change the uppercase variable to True.

For Loops to Iterate Over a Range

If you are familiar with other programming languages, you’ve probably noticed that the for loop in Python is different. In other languages, you typically iterate within a range of numbers (from 1 to n, from 0 to n, from n to m), not over a sequence. That said, you can also do this in Python by using the range() function.

For Loops With range()

First, you can use the range() function to repeat something a certain number of times. For example, let’s say you want to create a new password (password_new) consisting of 8 random characters. You can use the following for loop to generate 8 random characters and merge them into one string called password_new:

import random
import string
letters = string.ascii_letters
password_new = ''
for i in range(8):
    password_new += random.choice(letters)
print(password_new)

Output:
CvKYaEqi

In addition to the required stop argument (here, 8), the range() function also accepts optional start and step arguments. With these arguments, you can define the starting and the ending numbers of the sequence as well as the difference between each number in the sequence. For example, to get all even numbers from 4 to 10, inclusive, you can use the following for loop:

for i in range(4, 11, 2):
    print(i)
	
Output:
4
6
8
10

Note that we use 11, not 10, as the upper bound. The range() function does not include the upper bound in the output.

You may also use the range() function to access the iteration number within the body of the for loop. For example, let’s say we have a list of the student names ordered by their exam results, from the highest to the lowest. In the body of our for loop, we want to access not only the list values but also their index. We can use the range() function to iterate over the list n times, where n is the length of the list. Here, we calculate n by len(exam_rank):

exam_rank = ['Adele', 'James', 'Leonardo']
for i in range(len(exam_rank)):
    print(exam_rank[i], ' gets the #', i+1, ' result.', sep='')

Output:
Adele gets the #1 result.
James gets the #2 result.
Leonardo gets the #3 result.

Note that we use i+1 to print meaningful results, since the index in Python starts at 0.

For Loops With enumerate()

A “Pythonic” way to track the index value in the for loop requires using the enumerate() function. It allows you to iterate over lists and tuples while also accessing the index of each element in the body of the for loop:

exam_rank = ['Adele', 'James', 'Leonardo']
for place, student in enumerate(exam_rank, start = 1):
    print(student, ' gets the #', place, ' result.', sep='')
	
Output:
Adele gets the #1 result.
James gets the #2 result.
Leonardo gets the #3 result.

When combining the for loop with enumerate(), we have access to the current count (place in our example) and the respective value (student in our example) in the body of the loop. Optionally, we can specify the starting count argument to have it start from 1 as we have done, or from any other number that makes sense in your case.

Time to Practice For Loops in Python!

This is a general overview of the Python for loop just to quickly show you how it works and when you can use it. However, there is much more to learn, and even more importantly, you need lots of practice to master the Python for loop.

A good way to start practicing is with the Python courses that can be either free or paid. The course Python Basics. Part 1 is one of the best options for Python newbies. It covers all basic topics, including the for loop, the while loop, conditional statements, and many more. With 95 interactive exercises, this course gives you a strong foundation for becoming a powerful Python user. Here is a review of the Python Basics Course for those interested in learning more details.

If you’re determined to become a Python programmer, I recommend starting with the track Learn Programming with Python. It includes 5 courses with hundreds of interactive exercises, covering not only basics but also built-in algorithms and functions. They can help you write optimized applications and real Python games.

Thanks for reading and happy learning!