Skip to content

6.2 For in loop

6.2a Why do we use the for-in loop?

The for-in loop is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects.

 


 

6.2b How do we use the for-in loop?

Syntax:

for element in iterable:
    # code block to execute

for-in loop components:

  1. for - This keyword begins the for loop. It tells Python that you are starting a loop that will iterate over elements in an iterable.

  2. element - This is a variable that will take on the value of each item in the iterable, one at a time, during each iteration of the loop. You can name this variable anything you like, but it should be meaningful and descriptive.

  3. in - This keyword specifies that you are iterating over the elements of the iterable.

  4. iterable - This can be any Python object capable of returning its elements one at a time, such as a list, tuple, string, dictionary, set, or range. The for loop will iterate over each element of this iterable.

  5. colon (:) - This signifies the start of the code block that will be executed for each element in the iterable.

  6. code block to execute - This is the indented block of code that will be executed for each element in the iterable. The code block can consist of one or more statements.

Example 6.2.1

Please note that function range(5) generates a sequence of numbers starting from 0 up to, but not including, 5. So, range(5) produces the sequence [0, 1, 2, 3, 4].

for i in range(5):
    print(i)

Example 6.2.1 - Output

0
1
2
3
4

Example 6.2.1 - Output Visualisation or visualize this code here.

Iteration i value print(i) output
1 0 0
2 1 1
3 2 2
4 3 3
5 4 4

Example 6.2.1 - Explanation

  • The for-in loop iterates over each value generated by range(5), which are 0, 1, 2, 3, and 4.

  • During each iteration, the value of i is printed using print(i).

 


 

6.2c Why do we use range() with for loop?

  • Iteration Control - range() allows you to control how many times the loop will iterate or what values it will iterate over.

  • Sequence Generation - It generates a sequence of integers, making it useful for performing a task a specific number of times or iterating over a fixed range of values.

  • Efficiency - range() is memory efficient as it generates values on-the-fly rather than storing them all in memory.

Example 6.2.2 - Use case example with range function to iterate a fixed number of times. This loop will iterate 10 times, printing "Hello, iteration 0" through "Hello, iteration 9".

for i in range(10):
    print(f"Hello, iteration {i}")

Example 6.2.2 - Output

Hello, iteration 0
Hello, iteration 1
Hello, iteration 2
Hello, iteration 3
Hello, iteration 4
Hello, iteration 5
Hello, iteration 6
Hello, iteration 7
Hello, iteration 8
Hello, iteration 9

 


 

6.2d How the for-in loop works with a list?

Syntax:

for element in list_name:
    # Code to execute for each element

Here’s a breakdown of the components:

  • for: This keyword initiates the loop.
  • element: A variable name that will hold each value from the list as the loop iterates. You can choose any name for this variable.
  • in: This keyword is used to specify that we are iterating over the elements of the list.
  • list_name: The name of the list you want to iterate over.

 

Example 6.2.3 This example illustrates the basic usage of the for-in loop with a list.

numbers = [5, 10, 15, 20, 25]
for number in numbers:
    print(number)

Example 6.2.3 - Output

5
10
15
20
25

Example 6.2.3 - Output Visualisation or visualise this code here.

Iteration number value print(number) output
1 5 5
2 10 10
3 15 15
4 20 20
5 25 25

Example 6.2.3 - Explanation

  1. Initialization:

    • The for loop starts with the first element of the list, 5, and assigns it to the variable number.
  2. Iteration:

    • The loop executes the print(number) statement, outputting 5.
    • The loop then moves to the next element of the list, 10, assigns it to number, and repeats the process.
    • This continues until all elements in the list have been processed.
  3. Completion:

    • After the loop has processed the last element (25), it terminates, and the program continues with any code that follows the loop.

 

Example 6.2.4 - This example access indices in a list with the help of the range() function. This loop iterates over indices of my_list, printing each item and its index.

my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
    print(f"Index {i}: {my_list[i]}")

Example 6.2.4 - Output

Index 0: apple
Index 1: banana
Index 2: cherry

 


 

Exercise 6.2.1 - You are given a list of numbers. Write a Python program using a for loop that does the following:

  1. Iterates over each number in the list.
  2. Prints each number.
  3. Calculates the sum of all the numbers in the list and prints it at the end. Here is the list of numbers:

numbers = [10, 20, 30, 40, 50]

Exercise 6.2.1 - Model Answer - Make sure to work out the exercise before checking the model answer.