For Loops¶

Basic For Loops¶

A for loop allows you to perform an action repeatedly. The for loop specifies what the action is and how many times you perform the action.

This is the general structure of a for loop:

for [temporary variable] in [iterable data]:
       do action

Here are some important terms to understand when discussing for loops:

  • Iteration: The process of repeating an action.
  • Iterable object: An object, like a list, that can be iterated over during the loop, meaning that a for loop can go through (or traverse) each item in the object to perform an action.
  • Action: The code that is executed in each loop iteration.

Let's say we have a list of odd numbers, odds.

In [1]:
odds = [1, 3, 5, 7, 9]
odds
Out[1]:
[1, 3, 5, 7, 9]

You can print out the numbers in odds using a series of print statements.

In [2]:
print(odds[0])
print(odds[1])
print(odds[2])
print(odds[3])
print(odds[4])
1
3
5
7
9

However, this isn't a good approach to printing everything in a list. What if the list has 1000 values in it? That would be a lot of print statements to write. Instead, we can use a for loop to print the odd numbers.

In [3]:
for num in odds:
    print(num)
1
3
5
7
9

In terms of plain English, this is what the for loop does:

"For each number (num) in the odds list, print out that number."

The for loop visits each element in odds, starting with 1, then performs the action within the loop, which is printing the number. It then moves onto 3 and prints out that number. The for loop keeps doing this until the last element of the list is reached, then prints that last number and ends.

Here are some more examples of for loops:

In [ ]:
# Prints all the numbers of odd, multiplied by 2
for num in odds:
    print(num*2)
2
6
10
14
18
In [ ]:
# Counts the numbers in odds
count = 0
for num in odds:
    count = count + 1
print(count)
5
In [7]:
# Prints out a statement for each number in odds,
# even though the number itself isn't printed
for num in odds:
    print("I am a number!")
I am a number!
I am a number!
I am a number!
I am a number!
I am a number!
In [ ]:
# Prints the first letter of each country in the list
countries = ["Argentina", "Chile", "Brazil", "Ecuador"]
for country in countries:
    print(country[0])
A
C
B
E

Ranges¶

So far, we've been using lists in our for loops. However, you don't need a list to create a for loop! Instead, you can create a range of numbers to iterate over so that your for loop performs a specific number of times.

You can create a range using range() or np.arange().

For range(), you can either input a single number to represent the number of times you want the loop to run or provide a start and end (non-inclusive) number for the for loop to iterate across.

In [ ]:
# This for loop runs 5 times!
for num in range(5):
    print("Hello!")
Hello!
Hello!
Hello!
Hello!
Hello!
In [ ]:
# The standard range function starts at 0
for num in range(5):
    print("Number =", num)
Number =  0
Number =  1
Number =  2
Number =  3
Number =  4
In [ ]:
# This executes the same as the loop above,
# but it specifies start and end range values
for num in range(0, 5):
    print("Number =", num)
Number =  0
Number =  1
Number =  2
Number =  3
Number =  4
In [ ]:
# Another example
for num in range(5, 10):
    print("Number =", num)
Number =  5
Number =  6
Number =  7
Number =  8
Number =  9
In [ ]:
# Going up by 2!
for num in range(0, 5, 2):
    print("Number =", num)
Number =  0
Number =  2
Number =  4

np.arange() works similarly.

In [ ]:
import numpy as np
for num in np.arange(5):
    print("Number =", num)
Number =  0
Number =  1
Number =  2
Number =  3
Number =  4
In [ ]:
for num in np.arange(0, 5):
    print("Number =", num)
Number =  0
Number =  1
Number =  2
Number =  3
Number =  4

Enumerate¶

When we're iterating through a list, sometimes we want to extract both the value of an element, as well as the index of that same element. We can do that using enumerate().

Below is an example of enumerate():

In [3]:
# enumerate() example
enum_list = [3, 5, 8, 10]
for index, num in enumerate(enum_list):
    print(f"Iteration {index + 1}")
    print(f"Index: {index}")
    print(f"Number: {num}")
    print()
Iteration 1
Index: 0
Number: 3

Iteration 2
Index: 1
Number: 5

Iteration 3
Index: 2
Number: 8

Iteration 4
Index: 3
Number: 10

The structure of a for loop with enumerate() is slightly different than one with a simple list. Since the enumerate() function returns two outputs, we have two variables in our for loop, which were named index and num, corresponding to the index of the current list element and the value of the current list element, respectively.

Let's look at the first iteration of the for loop. We start at the first element of the list in this first iteration. When we print the value of index, it's 0, as the for loop starts at the starting element of index 0. When we print the value of num, we get 3, as that is the first number in the list. When we move to the next value in the list, the for loop returns the next index, 1, and the next value, 5. This repeats for all elements of the list, until we reach the last index, 3, and the last value, 10.

Nested For Loops¶

You can put a for loop within a for loop. This is called a nested for loop. In a nested for loop, for each iteration in the first loop, all the actions are performed in the second for loop.

In [28]:
# An example of a nested for loop
letters = ['s', 'k', 'a']
for num in range(5):
    for letter in letters:
        print(letter)
s
k
a
s
k
a
s
k
a
s
k
a
s
k
a

Some examples of nested for loops:

In [ ]:
# Prints out all the letters for each string in the list
houseplants = ['monstera', 'alocasia', 'pothos']
for plant in houseplants:
    for letter in plant:
        print(letter)
m
o
n
s
t
e
r
a
a
l
o
c
a
s
i
a
p
o
t
h
o
s
In [ ]:
# Prints out a combination of all the values in the two lists
list1 = ['A', 'B', 'C', 'D']
list2 = [0, 1, 2, 3]
for letter in list1:
    for number in list2:
        print("Letter-number combo is", letter, number)
Letter-number combo is A 0
Letter-number combo is A 1
Letter-number combo is A 2
Letter-number combo is A 3
Letter-number combo is B 0
Letter-number combo is B 1
Letter-number combo is B 2
Letter-number combo is B 3
Letter-number combo is C 0
Letter-number combo is C 1
Letter-number combo is C 2
Letter-number combo is C 3
Letter-number combo is D 0
Letter-number combo is D 1
Letter-number combo is D 2
Letter-number combo is D 3