Skip to main content

Python For Loop

Introduction

Loops are fundamental programming constructs that allow us to execute a block of code multiple times. In Python, the for loop is one of the most commonly used loop structures. It provides an elegant way to iterate over sequences (such as lists, tuples, dictionaries, sets, or strings) and other iterable objects.

Unlike for loops in languages like C or Java that typically iterate over numeric ranges, Python's for loop is designed to work with the iterator protocol, making it more versatile and easier to use.

Basic Syntax

The basic syntax of a Python for loop is:

python
for element in iterable:
# Code block to be executed for each element

Where:

  • element is a variable that takes the value of the item inside the iterable for each iteration
  • iterable is a collection of objects like lists, tuples, strings, etc.
  • The indented code block is executed once for each item in the iterable

Simple For Loop Examples

Iterating Through a List

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

In this example, the variable fruit takes on each value in the fruits list, and the print statement is executed for each value.

Iterating Through a String

Strings in Python are iterable sequences of characters:

python
message = "Hello"
for character in message:
print(character)

Output:

H
e
l
l
o

The range() Function

The range() function generates a sequence of numbers, which is commonly used with for loops when you need to repeat an action a specific number of times.

Basic Range

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

Output:

0
1
2
3
4

Note that range(5) produces numbers from 0 to 4 (not including 5).

Range with Start and Stop

python
for i in range(2, 6):
print(i)

Output:

2
3
4
5

Range with Step

You can also specify a step value:

python
for i in range(1, 10, 2):
print(i)

Output:

1
3
5
7
9

Nested For Loops

You can place a loop inside another loop to create nested loops:

python
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print() # Print a newline after each inner loop completes

Output:

(1, 1) (1, 2) (1, 3) 
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)

Loop Control Statements

The break Statement

The break statement terminates the loop prematurely:

python
for i in range(1, 10):
if i == 5:
break
print(i, end=" ")

Output:

1 2 3 4 

The continue Statement

The continue statement skips the current iteration and proceeds to the next one:

python
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ")

Output:

1 2 4 5 

The else Clause

Python allows an optional else clause with a for loop. The else block is executed when the loop completes normally (not terminated by a break):

python
for i in range(1, 6):
print(i, end=" ")
else:
print("\nLoop completed successfully!")

Output:

1 2 3 4 5 
Loop completed successfully!

If the loop is exited with a break, the else block is not executed:

python
for i in range(1, 6):
if i == 3:
break
print(i, end=" ")
else:
print("\nThis won't be printed!")

Output:

1 2 

Advanced For Loop Techniques

Using enumerate()

The enumerate() function adds a counter to an iterable:

python
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

Output:

0: apple
1: banana
2: cherry

Using zip()

The zip() function allows you to iterate through multiple iterables in parallel:

python
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")

Output:

Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

List Comprehension

List comprehensions provide a concise way to create lists using a for loop in a single line:

python
# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Practical Examples

Example 1: Finding Prime Numbers

A function to check if a number is prime using a for loop:

python
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False

i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True

# Print all prime numbers below 20
for num in range(1, 20):
if is_prime(num):
print(num, end=" ")

Output:

2 3 5 7 11 13 17 19 

Example 2: File Processing

Using a for loop to read and process a file line by line:

python
# Assuming you have a file named "sample.txt" with multiple lines
try:
with open("sample.txt", "r") as file:
line_number = 1
for line in file:
print(f"Line {line_number}: {line.strip()}")
line_number += 1
except FileNotFoundError:
print("The file doesn't exist.")

Example 3: Dictionary Iteration

Iterating through a dictionary:

python
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"David": 95
}

# Iterate through keys
for student in student_scores:
print(student)

print("\n---\n")

# Iterate through key-value pairs
for student, score in student_scores.items():
print(f"{student}'s score: {score}")

print("\n---\n")

# Iterate through values only
for score in student_scores.values():
print(score)

Output:

Alice
Bob
Charlie
David

---

Alice's score: 85
Bob's score: 92
Charlie's score: 78
David's score: 95

---

85
92
78
95

Summary

Python's for loop is a powerful and versatile tool for iteration that:

  • Iterates over any iterable object (lists, tuples, strings, dictionaries, etc.)
  • Can be used with the range() function to repeat code a specific number of times
  • Can be controlled with break, continue, and else clauses
  • Can be nested for more complex iterations
  • Works well with helper functions like enumerate() and zip()

Understanding and mastering the for loop is essential for writing efficient Python code and solving a wide range of programming problems.

Practice Exercises

  1. Write a program that calculates the sum and average of all numbers from 1 to 100 using a for loop.
  2. Create a program that prints the multiplication table (from 1 to 10) for a number input by the user.
  3. Write a function that counts how many vowels are in a string using a for loop.
  4. Create a nested for loop that prints a pattern of stars (*) forming a right-angled triangle.
  5. Write a program that finds all numbers between 1 and 1000 that are divisible by both 3 and 5.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)