Python for Loop

  • Python for loop is used to iterate over a sequence of items.
  • The for loop is implemented using the reserved keywordfor.
  • The for-loop code is executed for each element of the sequence.
  • We can get out of the for loop using the break statement.
  • We can use continue statement to skip the execution of the code in the for loop for an element.
  • Python for loop 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

Python for loop syntax is very simple. It uses in operator to iterate over the elements in the sequence.

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 for loop with different types of sequences.


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
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 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
Python for Loop With Tuple

Note: We are using a list to add elements in the for loop because 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
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
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
Python for Loop With Dictionary 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 break statement

Python for Loop with continue Statement

Sometimes we want to skip processing of some elements in the sequence. We can use 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 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 for 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 range() function

for Loop with else statement

We can use 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

Similarly, if the for loop is terminated using 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.

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 its 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 global scope

Normally, the variables defined inside a local namespace is 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 goes 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


Conclusion

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


References: