For loops

Coding with Python

🕑 This lesson will take about 30 minutes

A for loop allows you to repeatedly execute a block of code a specified number of times (eg. repeat an instruction 10 times) or iterate over a sequence (such as a string, list, tuple) or range of values. For loops are very useful for simplifying the process of repeatedly executing a block of code for each item in a sequence of range. For example, searching through all the elements in a list for a specific desired value, searching for a character in a string, or processing a data set (eg. converting strings in a list to lowercase format).

For loops are made up of two main components:

  • The iterable - is a sequence of items (like a list, tuple or a string) or range that you want to iterate over.

  • The temporary variable - stores the value of each item in the iterable during each iteration of the loop.

The code block inside the for loop is indented and contains the statements that will be executed each time the loop repeats, or for each item in the iterable.

Let’s check out some examples.

Example 1 - repeating a block of code

In this example, the loop is given a range to iterate through. The range is 10, meaning the loop will repeat 10 times. Each time the loop iterates, the variable i increases by 1 (with i taking values from 0 to 9). It is important to note that the variable will start counting from 0.

# Using a for loop to repeat a block of code 10 times
for i in range(10):
# Code to be executed for each iteration of the loop
print(i)
# Loop will repeat 10 times, with i taking values from 0 to 9
view raw for_loop1.py hosted with ❤ by GitHub

Example 2 - specifying a range

In this example, two values are provided for the range (5 and 15). This means the loop will repeat 10 times, with i taking values from 5 to 14.

# Using a for loop to repeat 10 times starting from 5
for i in range(5, 15):
# Code to be executed for each iteration of the loop
print(i)
# The loop will repeat 10 times, with i taking values from 5 to 14
view raw for_loop2.py hosted with ❤ by GitHub

Example 3 - iterate over a string

In this example, the for loop will iterate over each character in a string. Each time the loop iterates, the next character in the string is stored in the temporary variable named char (short for character). When the code runs, each individual character in the string "Hello world" will be displayed on a new line.

# Iterate over characters in a string
message = "hello world"
for char in message:
# Code to execute for each character in the string
print(f"Character: {char}")
view raw for_loop3.py hosted with ❤ by GitHub

Example 4 - iterate over a list

For loops can also be used to iterate over each element in a list. In the first example, we have a list of numbers. The for loop will iterate over each number in the list and display the square of that number (eg. “The square of 1 is 1…The square of 2 is 4…The square of 3 is 9”…etc.).

# Iterate over a list of elements (numbers)
numbers = [1, 2, 3, 4, 5]
for num in numbers:
# Code to be executed for each element in the list
squared = num ** 2
print(f"The square of {num} is {squared}")
view raw for_loop4.py hosted with ❤ by GitHub

In the next example, the for loop will iterate over a list of string values. The list is called names. For each iteration of the loop, the temporary variable called name will store the next element in the list. The loop also has an if statement that will search for a specific value in the list. In other words, for each element in the list, it will check if that element is equal to a certain value. If the target value (in this case, “wally”) is located in the list, the value stored in the variable called found is changed from False to True. After the loop ends, an if statement checks if the found variable is set to True and displays a message (eg. “Found Wally!”).

# Iterate over a list of elements (strings)
names = ["adam", "lily", "jack", "sophia", "wally", "jim"]
found = False
for name in names:
# Code to be executed for each element in the list
if name == "wally":
found = True
if found:
print("Found Wally!")
else:
print("Didn't find Wally")
view raw for_loop5.py hosted with ❤ by GitHub

Break a for loop

You can use the break keyword in a for loop to terminate the loop so it stops repeating. For example, you could have an if statement inside the for loop’s code block that tests a condition. If the condition evaluates to true, then you could write break to end the loop.

Next lesson: Operators