for Loop in Python

In this exercise, we will learn how to iterate over a sequence of elements using the different variations of for loop.

What is for loop in Python? In Python, a for loop is used to iterate (loop) over a sequence (like a list, tuple, string, dictionary, or range) and perform some actions repeatedly for each element.

Syntax of for Loop

for variable in sequence:
    # block of code

The function has the following parameters:

Example: Iterate over a list.

Python

# Create a list
fruits = ["apple", "banana", "cherry"]

# Print the list
print(fruits)

# Access an element in the list
print(fruits[0]) # output: apple

# Iterate over the list
for fruit in fruits:
    # print(fruit, end = ", ")
    print(fruit)

Output: ['apple', 'banana', 'cherry']
apple
apple
banana
cherry

Here, fruit takes values "apple", "banana", "cherry" one by one.

Example: Iterate over a string.

Python

# A string
name = "Ashish"

# Iterate over the string
for char in name:
    print(char)

Output: A
s
h
i
s
h

Example: Loop over dictionary.

Python

# Create a dictionary
student = {"name": "Ashish", "age": 29, "subject": "Python"}

# Iterate over a dictionary
for item in student:
    print(item, ":", student[item]) 

Output: name : Ashish
age : 29
subject : Python

We are iterating over a sequence in the for loop, if we want to use for loop for a specific number of times, we can use the range() function.

The range() function The range function generates a sequence of numbers.

Syntax range (start, stop, step)

The function has the following parameters:

Example: Iterate a range.

Python

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

Output 0
1
2
3
4

Here, we can see that the loop starts from 0 by default and increments at each iteration.

But we can also loop over a specific range.

Example: Loop over a specific range.

Python

for k in range(4,9):
    print(k) 

Output 4
5
6
7
8

Example: Loop over a specific range with step.

Python

for k in range(0,9, 2):
    print(k)

Output 0
2
4
6
8

Example: Iterate over all the elements in the sequence.

Python

# Create a list
my_list = ["Ashish", "Katrina", "Alia", "Jacky"]

# Iterate over the list using index
for item in range (len(my_list)):
    print(my_list[item])

Output Ashish
Katrina
Alia
Jacky

Example: Iterate over a specific number of times.

Python

# Create a list
my_list = ["Ashish", "Katrina", "Alia", "Jacky"]

# Iterate over the list using index
for item in range (2):
    print(my_list[item])

Output Ashish
Katrina

For Loop with Multiple Variables If each element of the iterable is a sequence (like a tuple or list), you can assign each part of that sequence to separate loop variables.

This is very useful when working with lists of tuples, dictionaries, or functions like enumerate() or os.walk().

Syntax

for var1, var2, ... in iterable:
    # loop body

Example: List of Tuples.

Python

pairs = [(1, "one"), (2, "two"), (3, "three")]

for number, word in pairs:
    print(f"Number: {number}, Word: {word}")

Output Number: 1, Word: one
Number: 2, Word: two
Number: 3, Word: three

Explanation: • Each tuple (1, "one") is unpacked into number and word.

Example: List of Lists.

Python

coordinates = [[10, 20], [30, 40], [50, 60]]

for x, y in coordinates:
    print(f"x={x}, y={y}")

Output x=10, y=20
x=30, y=40
x=50, y=60

Example: Using enumerate().

Python

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

Output 0: apple
1: banana
2: cherry

Explanation:

Example: Using os.walk() method.

Python

import os

ROOT_DIR = "my_project"

for root, dirs, files in os.walk(ROOT_DIR):
    print("Current folder:", root)
    print("Subfolders:", dirs)
    print("Files:", files)

Explanation: