Python for Loop

Python for loop is used to iterate over an iterable. Any object that returns its elements one by one to be iterated over a for loop is called Iterable in Python. Some of the common examples of iterables are List, Tuple, and String. The for loop is the core building block of python programming.

Implementing for loop in Python

The for loop in Python is implemented using the reserved keywordfor. The for-loop code block is executed for each element of the iterable.

Exiting for loop

We can get out of the for loop using the break statement. This will terminate the for loop execution and the code block won’t be executed for the remaining elements of the iterable. This is useful when we found what we are looking for and don’t need to process other elements of the iterable.

Skipping Current Execution of for loop

We can use the continue statement to skip the current execution of the for loop. This is useful when we want to execute the code only for some specific elements of the iterable.

Python for loop is an iterator?

The for loop in Python is different from other programming languages as it behaves more like an iterator. We can use for loop to iterate over Tuple, List, Set, or String. All of these objects are a sequence in Python. We can have nested for loops to iterate over a sequence of sequences.


Python for Loop Syntax

The for loop syntax is very simple. It uses the “in” operator to iterate over the elements in the iterable.

for element in sequence:
    # for statement code block

Flow Diagram of for Loop

For Loop Flow Diagram
For Loop Flow Diagram

Python for loop Examples

Let’s look into some examples of the for loop with different types of iterables.


1. String

Python string is a sequence of characters. Let’s look at a simple program to print the index and character in a string.

message = "Hello"

count = 0
for character in message:
    print(f'Index:{count}, Character:{character}')
    count += 1

Output:

Python For Loop Example String

2. Tuple

Let’s say we have a tuple of strings. We want to convert all the elements to lowercase. We can write a utility function for this and use the for loop to iterate over the tuple elements.

def to_lower_case(my_tuple):
    temp_list = []
    for item in my_tuple:
        temp_list.append(str(item).lower())
    return tuple(temp_list)


fruits = ("Apple", "Orange", "BANANA")
fruits_new = to_lower_case(fruits)
print(fruits_new)

Output: ('apple', 'orange', 'banana')

Python For Loop With Tuple

Note: We are using a list to add elements in the for-loop because the Tuple is immutable in Python.


3. List

Let’s look at an example of iterating over the list of integers and print if it’s an even number or an odd number.

list_ints = [1, 2, 3, 4, 5]
for i in list_ints:
    if i % 2 == 0:
        print(f'{i} is even.')
    else:
        print(f'{i} is odd.')

Output:

Python For Loop With List

4. Set

Here is a simple example to print the elements of a set using for loop.

set_cities = set()
set_cities.add("New York")
set_cities.add("New Delhi")
set_cities.add("Bangalore")
set_cities.add("London")
set_cities.add("Bangalore")  # duplicate item, will be removed from set

for city in set_cities:
    print(city)

Output:

Python For Loop With Set

Note: Set is an unordered sequence in Python. So the output might vary in every execution of the program.


5. Dictionary

Python dictionary is not a sequence. So we can’t iterate over its elements directly. However, it has a method items() that returns a set-like sequence of its elements. We can use this method to iterate over the dictionary elements.

my_dict = {"1": "Apple", "2": "Kiwi", "3": "Orange"}

for k, v in my_dict.items():
    print(f'Key={k}, Value={v}')

Output:

Python For Loop With Dict Items

Using break Statement to Exit for Loop

We can use the break statement to exit for loop without iterating all the elements.

Let’s say we have a list of messages to process. If we encounter the “Exit” message then the processing should stop. We can use the break statement to implement this scenario.

messages = ["Hi", "Hello", "Exit", "Adios", "Hola"]

for msg in messages:
    if msg == "Exit":
        break;
    print(f'Processing {msg}')

Output:

Python For Loop Break

Python for Loop with continue Statement

Sometimes we want to skip the processing of some elements in the sequence. We can use a continue statement for this.

ints = (1, 2, 3, 4, 5, 6)

# process only odd numbers
for i in ints:
    if i % 2 == 0:
        continue
    print(f'Processing {i}')

Output:

Python For Loop With Continue Statement

Python for loop with range() function

Python range() function generates a sequence of numbers. We can use this with for loop to execute a code block a specific number of times.

Let’s see how to use range() function with for loop to execute a code 5 times.

for i in range(5):
    print("Processing for loop:", i)

Output:

Python For Loop With Range Function

Python for Loop with else statement

We can use the else statement with for loop to execute some code when the for loop is finished.

It’s useful in logging or sending a notification when the processing of a sequence is successfully completed.

databases = ("MySQL", "Oracle", "PostgreSQL", "SQL Server")

for db in databases:
    print(f'Processing scripts for {db}')
else:
    print("All the databases scripts executed successfully.")

Output:

Else With For Loop In Python
else with for Loop in Python

Note: If the for loop raises any error, then the else block code is not executed.

databases = ("MySQL", "Oracle", "PostgreSQL", "SQL Server")

for db in databases:
    print(f'Processing scripts for {db}')
    raise TypeError
else:
    print("All the databases scripts executed successfully.")

Output:

Processing scripts for MySQL
Traceback (most recent call last):
  File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/for-loop.py", line 65, in <module>
    raise TypeError
TypeError

If the for loop is terminated using a break statement then the else block is not executed.


Nested for Loops in Python

When a loop is present inside another loop, it’s called a nested loop. Python for loops can be nested. It’s useful in iterating over nested iterables, for example, a list of lists.

list_tuples = [("Apple", "Banana"), ("Orange", "Kiwi", "Strawberry")]

for t_fruits in list_tuples:
    for fruit in t_fruits:
        print(fruit)

Output:

Nested For Loop In Python
Nested for Loop In Python

Reverse Iteration using for Loop and reversed() function

The for loop iterates through the sequence elements in the order of their occurrence. Sometimes we have to iterate through the elements in the reverse order. We can use reversed() function with the for loop to achieve this.

numbers = (1, 2, 3, 4, 5)

for n in reversed(numbers):
    print(n)

Output:

5
4
3
2
1

The for-loop variables leaking to the global scope

Normally, the variables defined inside a local namespace are not accessible outside. As soon as the code block finishes its execution, the local namespace is destroyed along with all its variables. But, it’s not true with the for-loop.

The variables defined inside the for loop go in the global scope. We can even access and change global namespace variable values inside the for loop. Let’s check this behavior with a simple code snippet.

global_var = "global"
for c in range(1,3):
    x = 10
    global_var = "for variable"

print(c)  # variable is defined in the for loop
print(x)  # variable is defined in the for loop
print(global_var)  # global variable
Python For Loop Global Variables
Python for Loop Global Variables

Recommended: Python Namespace


Summary

Python for loop works as an iterator. We can use it to iterate over the iterable elements. We can have nested for loops to iterate over an iterable of iterables. There are some additional functions – range() and reversed() that makes it more powerful.

What’s Next?


References: