Python for Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) or any iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.


Basic Syntax

for item in sequence:
    # Code block to execute for each item
  • item: Represents the current element in the sequence.
  • sequence: An iterable object like a list, tuple, string, or range.

Example: Iterating Over a List

names = ["Aarav", "Nisha", "Kiran"]
for name in names:
    print("Hello, " + name + "!")

Output:

Hello, Aarav!
Hello, Nisha!
Hello, Kiran!

Using range() in a for Loop

The range() function generates a sequence of numbers, which is commonly used with for loops.

Syntax of range():

range(start, stop, step)
  • start: The starting number (default is 0).
  • stop: The number where the sequence ends (exclusive).
  • step: The increment or decrement value (default is 1).

Examples with range()

Example 1: Simple Range

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

Output:

0
1
2
3
4

Example 2: Custom Start and Stop

for num in range(1, 6):
    print(num)

Output:

1
2
3
4
5

Example 3: Using Step

for num in range(0, 10, 2):
    print(num)

Output:

0
2
4
6
8

Example 4: Reverse Range

for num in range(10, 0, -2):
    print(num)

Output:

10
8
6
4
2

Iterating Over Different Data Types

The for loop can work with any iterable object, such as strings, lists, tuples, dictionaries, and sets.

1. Iterating Over a String

website = "pythonforall"
for char in website:
    print(char)

Output:

p
y
t
h
o
n
f
o
r
a
l
l

2. Iterating Over a Dictionary

When iterating over a dictionary, you can access keys and values.

Example:

student_scores = {"Aman": 85, "Neha": 92, "Ravi": 78}
for name in student_scores:
    print(name + " scored " + str(student_scores[name]))

Output:

Aman scored 85
Neha scored 92
Ravi scored 78

3. Iterating Over a Set

A for loop can iterate through a set, but the order of elements is not guaranteed.

Example:

unique_numbers = {3, 1, 4, 2}
for num in unique_numbers:
    print(num)

Nested for Loops

You can use one for loop inside another to iterate through nested sequences like lists of lists.

Example:

matrix = [[1, 2], [3, 4], [5, 6]]
for row in matrix:
    for num in row:
        print(num, end=" ")

Output:

1 2 3 4 5 6

Using else with a for Loop

In Python, the for loop can have an else block. The code inside the else block executes after the loop finishes, but not if the loop is exited early with a break statement.

Example 1: Without break

names = ["Aarav", "Nisha", "Kiran"]
for name in names:
    print("Processing " + name)
else:
    print("All names processed successfully!")

Output:

Processing Aarav
Processing Nisha
Processing Kiran
All names processed successfully!

Example 2: With break

names = ["Aarav", "Nisha", "Kiran"]
for name in names:
    if name == "Nisha":
        print("Skipping " + name)
        break
    print("Processing " + name)
else:
    print("All names processed successfully!")

Output:

Processing Aarav
Skipping Nisha

Advanced Example: Printing Multiples of 3

Using for-else to find numbers:

numbers = [3, 6, 9, 12, 15]
 
for num in numbers:
    if num % 3 != 0:
        print("Found a non-multiple of 3: " + str(num))
        break
else:
    print("All numbers are multiples of 3.")

Output:

All numbers are multiples of 3.

Try It Yourself

Problem 1: Using for with range()

Write a program to print all odd numbers from 1 to 10.

Show Code
for num in range(1, 11, 2):
    print(num)

Problem 2: Iterating Over a String

Write a program to count the number of vowels in "pythonforall".

Show Code
text = "pythonforall"
vowels = "aeiou"
count = 0
 
for char in text:
    if char in vowels:
        count += 1
 
print("Number of vowels:", count)

Problem 3: Using for-else

Write a program to check if a specific name is present in a list of names.

Show Code
names = ["Aman", "Riya", "Kunal", "Meera"]
target_name = "Riya"
 
for name in names:
    if name == target_name:
        print(target_name + " is in the list.")
        break
else:
    print(target_name + " is not in the list.")

Pyground

Play with Python!

Output: