NavigationContentFooter
Jump toSuggest an edit

Getting started with Python for loops - A comprehensive guide with exercises

Reviewed on 17 July 2024Published on 28 June 2023
  • python
  • loops
  • syntax
  • programming
Requirements

If you’re coming to this tutorial as a complete Python beginner, make sure you are familiar with the Python concepts covered in our Python for complete beginners tutorial, and with dictionaries and lists.

Introduction

So you know how to create variables in Python, as well as how to create lists and dictionaries to store multiple items in a single variable? Then you are ready to learn about loops.

A loop is a piece of code that tells Python to repeat a specified set of actions multiple times. Loops are a fundamental part of most programming languages, and let you achieve a lot with just a few lines of code. Often, they iterate over collections of data (such as data held in dictionaries or lists) and carry out all sorts of operations on those collections.

Why are loops useful? Let’s look at a quick example:

Imagine you have a list of numbers, and you want to find every number higher than 10. Without a loop, the code is very long and repetitive:

my_list = [3, 10.1, 62, 9]
if my_list[0] > 10:
print(my_list[0])
if my_list[1] > 10:
print(my_list[1])
if my_list[2] > 10:
print(my_list[2])
if my_list[3] > 10:
print(my_list[3])
## Output:
10.1
62

With a for loop, we can do it in just three lines of code:

for number in my_list:
if number > 10:
print(number)
## Output:
10.1
62

Let’s dive into the world of for loops in Python, and learn how to code them and what we can do with them.

Note

There are two types of loops in Python:

  • while-loops repeat while a certain condition is true and exit once the condition is false.
  • for-loops iterate over a sequence or collection of data and exit when they reach the end of the sequence/collection. This tutorial concerns only for loops.

Before you start

To complete the actions presented below, you must have:

  • Installed Python on your machine
  • Knowledge of how to execute Python commands and see their output, using for example either the Python Interactive Shell, a text editor and the terminal, or another method such as Jupyter notebook
  • Familiarity with the basics of if statements, operators, lists, and dictionaries in Python

For loop syntax and basic examples

The syntax for a for loop is as follows:

for element in iterable-object:
statement(s)

Here are some basic examples of loops iterating over different types of objects:

my_list = ["red", "blue", "yellow"]
for color in my_list:
print(color)
## output:
red
blue
yellow

Ingredients of a for loop (see the syntax above):

  • for: this keyword is required to start a loop
  • element: after the for keyword, we can use any variable name we want. This variable will simply access each item of the sequence on each iteration. In the examples above you can see that we’ve called it variously element, color, letter, product, and x. Anything works, but generally you should try to give this variable a meaningful name: it will make your code easier to read for yourself and anyone else who looks at it.
  • in: this keyword is required to introduce the object you want to iterate over in the loop
  • iterable-object: after the in keyword, state the object you want to iterate over. This can be any iterable object, including lists, strings, dictionaries, ranges, tuples, and sets.
  • The for statement must end with a colon, followed by a line return and indentation.
  • statement(s): One or more actions to be carried out on every iteration of the loop. In the examples above we simply use a print statement, but anything is possible.

Basic exercises

Tip

When working with loops, you will probably find it more practical to use a text editor and the terminal or Jupyter notebook / other IDE, rather than the Python Interactive Shell.

  1. Run the following code to get started with your first loop, making sure to include all the necessary syntax such as the colon and indentation:

    my_list = ["red", "blue", "yellow"]
    for color in my_list:
    print(color)
  2. Run the following loop, to see how you can define the iterable object directly in the loop statement itself:

    for country in ["France", "Japan", "USA"]:
    print(country)
  3. Using the example of a loop with a range as shown above, create a loop that prints out the numbers 1 to 6. The output should look like this:

    1
    2
    3
    4
    5
    6

    Answer below.

  4. Using the example of looping over a string as shown above, create a loop that prints out the letters A B C D E. The output should look like this:

    A
    B
    C
    D
    E

    Answer below.

  5. Using the example of looping over a dictionary as shown above, create a dictionary {"France": "Paris", "Japan": "Tokyo", "USA": "Washington DC"}, then:

    • Create a loop that prints out the names of the countries
    • Create a loop that prints out the names of the capital cities

    The output should look like this:

    France
    Japan
    USA
    Paris
    Tokyo
    Washington DC

    Answer below.

For loops with an if/else statement

We can use an if/else statement inside the loop to deal with different possibilities:

for number in [1, 10, 9, 4]:
if number > 5:
print(number, " is greater than 5")
else:
print(number, " is not greater than 5")
## Output:
1 is not greater than 5
10 is greater than 5
9 is greater than 5
4 is not greater than 5
Tip

Note that in the example above, we can print a variable and some text in the same string by separating them with commas and putting the text in quotation marks:

print(variable_name, " text you want here", another_variable_name, " more text here")

If/else exercises

  1. Create a loop that iterates over the list [1, 10, 9, 4] and checks whether each number is greater than 3. The output should look like this:

    1 is not greater than 3
    10 is greater than 3
    9 is greater than 3
    4 is greater than 3

    Answer below.

  2. Create a loop that iterates over the list ["France", "Japan", "the USA"] and searches for “the USA” in the list. The output should look like this:

    This country is not the USA
    This country is not the USA
    This country is the USA

    Answer below.

  3. Create a loop that iterates over the list [-1, 2, 3, 0, -4] and checks whether each number is positive or negative. The output should look like this:

    -1 is a negative number
    2 is a positive number
    3 is a positive number
    0 is neither positive nor negative
    -4 is a negative number

    Answer below.

For loops with a range() function

As we saw in an earlier example we can use loops with Python’s built-in range() function to state exactly how many times we want the loop to iterate.

This function can be used in many ways:

With just one parameter, the range starts at a default of 0 and finishes at (not including) the specified number:

for x in range(3):
print(x)
## Output:
0
1
2

With two parameters, we set the start and finish numbers of the range:

for x in range(2, 6):
print(x)
## Output:
2
3
4
5

With three parameters, we set the start and finish numbers of the range, and the step value (the interval between each iteration):

for x in range(2, 10, 2):
print(x)
## Output:
2
4
6
8

Range exercises

  1. Create a loop that iterates over a range and produces the following output:

    5
    6
    7
    8
    9

    Answer below.

  2. Create a loop that iterates over a range and produces the following output:

    0
    25
    50
    75

    Answer below.

  3. Create code that includes a loop that iterates over a range, and produces the following output:

    Counting down...
    5
    4
    3
    2
    1
    Go!

    Answer below.

Nested for loops

We can use a loop inside another loop: this is called a nested loop. This is useful if, for example, you want to loop through a list of lists:

groups = [["Kendall", "Shiv", "Roman"], ["Logan", "Ewan", "Gerri"], ["Tom", "Greg"]]
# this first loop iterates through each group:
for group in groups:
# this second loop iterates through the people in each group:
for person in group:
## we can access both the 'group' and 'person' variables here!
print(person, "is in the group", group)
## Output:
Kendall is in the group ['Kendall', 'Shiv', 'Roman']
Shiv is in the group ['Kendall', 'Shiv', 'Roman']
Roman is in the group ['Kendall', 'Shiv', 'Roman']
Logan is in the group ['Logan', 'Ewan', 'Gerri']
Ewan is in the group ['Logan', 'Ewan', 'Gerri']
Gerri is in the group ['Logan', 'Ewan', 'Gerri']
Tom is in the group ['Tom', 'Greg']
Greg is in the group ['Tom', 'Greg']

Nested loop exercises

  1. Create code with a nested loop based on the list of lists [["apple", "orange"], ["carrot", "cabbage"], ["chicken", "beef"]] and produces the following output:

    apple
    orange
    carrot
    cabbage
    chicken
    beef

    Answer below.

  2. Create code with a nested loop based on the list of lists [["go", "went", "gone"], ["see", "saw", "seen"], ["take", "took", "taken"]] that produces the following output:

    The conjugations of go are:
    go
    went
    gone
    The conjugations of see are:
    see
    saw
    seen
    The conjugations of take are:
    take
    took
    taken

    Answer below.

  3. Create code with a nested loop that searches the list of lists [["50", "48", "-40"], ["57", "99", "80"], ["49, 40, 45"]] and prints out all the numbers greater than or equal to 50. The output should look like this:

    50
    57
    99
    80

    Answer below.

Break and continue statements in for loops

A break statement can be used to exit a loop before all the iterations have finished. We might want to do this when a certain condition is met, and there is no value to continuing to loop.

In the example below, we want to check whether a list contains the word “bingo”:

words = ["tennis", "poker", "bingo", "chess"]
for word in words:
if word == "bingo":
print("The list contains the word bingo")
break
## Output:
The list contains the word bingo

Alternatively, a continue statement can be used to skip the remaining code inside the loop for the current iteration. We might want to do this when a certain condition is not met, and there is no value to continuing the rest of the code for this iteration.

In the example below we want to find words with first letter “b” and last letter “o”:

words = ["tennis", "poker", "bingo", "chess"]
for word in words:
if word[0] != "b":
continue
else:
if word[-1] == "o":
print("The word", word, "starts with b and ends with o")
## Output:
The word bingo starts with b and ends with o.

Break and continue exercises

  1. Create a loop to check whether the list [3, 5, 11, 12, 1] contains at least one number higher than 10, and print “This list contains a number higher than 10” if it does. Include a break statement. The output should be as follows:

    This list contains a number higher than 10

    Answer below.

  2. Create a loop to check whether the list of lists [[1, 3, 9], [3, 2], [4, 2] contains any lists that a) contain exactly two items, and b) the sum of the items is not greater than 5. Include a continue statement. The output should be as follows:

    [3, 2] contains two items which have a sum no greater than 5

    Answer below.

Manipulating variables with for loops

Let’s imagine we want to check whether a particular word is in a list. We could use a loop as shown below:

words = ["tennis", "poker", "bingo", "chess"]
for word in words:
if word == "bingo":
print("bingo is in the list")
## output:
bingo is in the list

However, there are two problems:

  • If the word “bingo” was in the list multiple times, we risk printing the statement multiple times when it is not necessary (though we could solve this with a break statement)
  • If the word “bingo” wasn’t on the list, nothing would be printed. This is not very explicit and might lead us to wonder if the code worked properly or not.

We can improve this by using a variable that we create outside the loop and conditionally modify inside the loop. It then has a useful, meaningful value once the loop has finished:

words = ["tennis", "poker", "bingo", "chess"]
bingo_in_list = False
for word in words:
if word == "bingo":
bingo_in_list = True
if bingo_in_list == True:
print("The list contains the word bingo")
else:
print("The list does not contain the word bingo")
## Output:
The list contains the word bingo

Another common practice is to instantiate a variable outside a list, and use it to “collect” certain information from inside the loop. The following example shows how we can create a list containing all the words beginning with C from another list:

words = ["deranged", "anger", "cowardly", "things", "abject", "cuddly", "rhyme", "bed", "harm"]
c_words = []
for word in words:
if word[0] == "c":
c_words.append(word)
print(c_words)
## Output:
['cowardly', 'cuddly']
Important

It is bad practice to modify a list (or dictionary, or any other sequence) while you are iterating over it. For example, we could try to achieve the above task by removing words in the list when they do not start with c, but as words are removed mid-loop, the length of the list changes and this confuses the iterator, which ends up missing out some words as according to their index postion, they have already been checked. The output would therefore be inaccurate.

For this reason, you should always follow the example above, and use separate variables to collect data from the sequence you are iterating over.

Variable exercises

  1. Create code that includes a loop which iterates over the list [1, 5, 2, 6] and prints “The sum of the numbers in the list is 14” at the end. Use the += operator, and a variable which is instantiated outside the loop, but modified inside it.

    The sum of the numbers in the list is 14

    Answer below

  2. Create code that includes a loop which iterates over the list [1, 5, 2, 6] and prints “The highest number in this list is 6” at the end. Use a variable which is instantiated outside the loop, but modified inside it.

    The highest number in the list is 6

    Answer below

  3. Create code that includes a loop which iterates over the list [3, 6, 1, 2, 5] and creates a new list called doubled which holds the double of each number, i.e. [6, 12, 2, 4, 10] and prints it. Use a variable which is instantiated outside the loop, but modified inside it.

    [6, 12, 2, 4, 10]

    Answer below

  4. Create code that includes a loop which iterates over the dictionary {"bread": 1.5, "jam": 2.75, "butter": 0.99, "sugar": "0.75"} and creates two lists as shown below. Print both lists at the end. Use variables which are instantiated outside the loop, but modified inside it.

    Items that cost less than 1 euro: [butter, sugar]
    Items that cost more than (or exactly) 1 euro: [bread, jam]

    Answer below

Answers

Note

The name of the loop variable (x, country, number etc.) could be different in your answers.

Basic exercises: answers

3: Create a loop with a range statement, that prints out the numbers 1 to 6:

for x in range(1,7):
print(x)
## output:
1
2
3
4
5
6

4: Create a loop that prints out the letters A B C D E:

for x in "ABCDE":
print(x)
## output:
A
B
C
D
E

5a: Create a dictionary {"France": "Paris", "Japan": "Tokyo", "USA": "Washington DC"}, then create a loop that prints out the name of the countries, then another that prints out the names of the capital cities.

countries = {"France": "Paris", "Japan": "Tokyo", "USA": "Washington DC"}
for country in countries:
print(country)
## output:
France
Japan
USA
for country in countries:
print(countries.get(country))
## output:
Paris
Tokyo
Washington DC

If/else exercises: answers

1: Create a loop that iterates over the list [1, 10, 9, 4] and checks whether each number is greater than 3:

numbers = [1, 10, 9, 4]
for number in numbers:
if number>3:
print(number, "is greater than 3")
## output:
1 is not greater than 3
10 is greater than 3
9 is greater than 3
4 is greater than 3

2: Create a loop that iterates over the list ["France", "Japan", "the USA"] and searches for “the USA” in the list:

countries = ["France", "Japan", "the USA"]
for country in countries:
if country=="the USA":
print("This country is the USA")
else:
print("This country is not the USA")
## output:
This country is not the USA
This country is not the USA
This country is the USA

3: Create a loop that iterates over the list [-1, 2, 3, 0, -4] and checks whether each number is positive or negative:

numbers = [-1, 2, 3, 0, -4]
for number in numbers:
if number > 0:
print(number, "is a positive number")
elif number < 0:
print(number, "is a negative number")
else:
print(number, "is neither positive nor negative")
## output:
-1 is a negative number
2 is a positive number
3 is a positive number
0 is neither positive nor negative
-4 is a negative number

Range exercises: answers

1: Create a loop that iterates over a range and produces the output shown below:

for x in range(5,10):
print(x)
## output:
5
6
7
8
9

2: Create a loop that iterates over a range and produces the output shown below:

for x in range(0,100,25):
print(x)
## output:
0
25
50
75

3: Create code that includes a loop that iterates over a range and produces the output shown below:

print("Counting down")
for x in range(5,0,-1):
print(x)
print("Go!")
## output:
Counting down...
5
4
3
2
1
Go!

Nested for loop exercises: answers

1: Create code with a nested loop based on the list of lists [["apple", "orange"], ["carrot", "cabbage"], ["chicken", "beef"]] which produces the output shown below:

for group in foods:
for item in group:
print(item)
## output:
apple
orange
carrot
cabbage
chicken
beef

2: Create code with a nested loop based on the list of lists [["go", "went", "gone"], ["see", "saw", "seen"], ["take", "took", "taken"]] that produces the output shown below:

conjugations = [["go", "went", "gone"], ["see", "saw", "seen"], ["take", "took", "taken"]]
for group in conjugations:
print("The conjugations of ", group[0], " are:")
for conjugation in group:
print(conjugation)
## output:
The conjugations of go are:
go
went
gone
The conjugations of see are:
see
saw
seen
The conjugations of take are:
take
took
taken

3: Create code with a nested loop that searches the list of lists [[50, 48, -40], [57, 99, 80], [49, 40, 45]] and prints out all the numbers greater than or equal to 50:

numbers=[[50, 48, -40], [57, 99, 80], [49, 40, 45]]
for group in numbers:
for number in group:
if number >=50:
print(number)
## output:
50
57
99
80

Break and continue exercises: answers

1: Create a loop to check whether the list [3, 5, 11, 12, 1] contains at least one number higher than 10, and print “This list contains a number higher than 10” if it does. Include a break statement. The output should be as shown below.

numbers = [3, 5, 11, 12, 1]
for number in numbers:
if number > 10:
print("This list contains a number higher than 10")
break

2: Create a loop to check whether the list of lists [[1, 3, 9], [3, 2], [4, 2]] contains any lists that a) contain exactly two items, and b) the sum of the items is not greater than 5. Include a continue statement. The output should be as shown below:

numbers = [[1, 3, 9], [3, 2], [4, 2, 1, 3]]
for group in numbers:
if len(group) != 2:
continue
elif sum(group) <= 5:
print(group, "contains two items which have a sum no greater than 5")
## output:
[3, 2] contains two items which have a sum no greater than 5

Variable exercises: answers

1: Create code that includes a loop which iterates over the list [1, 5, 2, 6] and prints “The sum of the numbers in the list is 14” at the end. Use the += operator, and a variable which is instantiated outside the loop, but modified inside it.

numbers = [1, 5, 2, 6]
sum_of_numbers = 0
for number in numbers:
sum_of_numbers += number
print("The sum of numbers in the list is", sum_of_numbers)
## output:
The sum of the numbers in the list is 14

2: Create code that includes a loop which iterates over the list [1, 5, 2, 6] and prints “The highest number in this list is 6” at the end. Use a variable which is instantiated outside the loop, but modified inside it.

numbers = [1, 5, 2, 6]
max_number = numbers[0]
for number in numbers:
if number > max_number:
max_number = number
print("The highest number in the list is", max_number)
## output:
The highest number in the list is 6

3:. Create code that includes a loop which iterates over the list [3, 6, 1, 2, 5] and creates a new list called doubled which holds the double of each number, i.e. [6, 12, 2, 4, 10] and prints it. Use a variable which is instantiated outside the loop, but modified inside it.

numbers = [3, 6, 1, 2, 5]
doubled = []
for number in numbers:
doubled.append(number *2)
print(doubled)
## output:
[6, 12, 2, 4, 10]

4: Create code that includes a loop which iterates over the dictionary {"bread": 1.5, "jam": 2.75, "butter": 0.99, "sugar": 0.75} and creates two lists which are printed as shown below. Use variables which are instantiated outside the loop, but modified inside it.

items = {"bread": 1.5, "jam": 2.75, "butter": 0.99, "sugar": 0.75}
less_1 = []
more_1 = []
for item in items:
if items.get(item) < 1:
less_1.append(item)
else:
more_1.append(item)
print("Items that cost less than 1 euro:", less_1)
print("Items that cost more than (or exactly) 1 euro:", more_1)
## output:
Items that cost less than 1 euro: ['butter', 'sugar']
Items that cost more than (or exactly) 1 euro: ['bread', 'jam']
API DocsScaleway consoleDedibox consoleScaleway LearningScaleway.comPricingBlogCareers
© 2023-2024 – Scaleway