Python for
Loop
In Python, the for
loop is a versatile and powerful tool for iterating over sequences like lists, strings, and ranges. It allows you to repeat a block of code a certain number of times or process each item in a collection. Whether you’re a beginner or an experienced developer, mastering the for
loop will make your coding much more efficient.
In this blog post, we will explore how the for
loop works in Python, different ways to use it, and practical examples to help you get started.
for
Loop in Python?A for
loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence. Unlike other programming languages, Python’s for
loop is not just a counter-based loop; it directly works with the elements of a collection.
for
Loop:
for item in sequence:
# Code to execute for each item
item
is the variable that takes the value of the current element in the sequence.sequence
is the collection (list, string, range, etc.) you want to loop over.for
Loop with ListsLists are one of the most common sequences used with for
loops. When you iterate over a list, the loop executes the block of code for each item in the list.
# Example: Iterating through a list
fruits = ['apple', 'banana', 'cherry', 'date']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
date
In this example:
fruits
list and prints it.for
Loop with StringsStrings are also iterable, meaning you can loop over each character in a string.
# Example: Iterating through a string
word = "Python"
for char in word:
print(char)
Output:
P
y
t
h
o
n
Here:
for
loop iterates over each character in the string "Python" and prints each character on a new line.for
Loop with range()
The range()
function generates a sequence of numbers, which can be used to control the number of iterations in a loop. It’s often used when you want to repeat a block of code a certain number of times.
range()
# Example: Using range() with for loop
for i in range(5):
print(i)
Output:
0
1
2
3
4
Here:
range(5)
function generates a sequence of numbers from 0 to 4.You can also specify a starting point and step size in range()
. For example, range(2, 10, 2)
generates the numbers 2, 4, 6, 8.
range()
with Custom Start and Step
# Example: Using range() with custom start and step
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
for
LoopsA nested for
loop is a loop inside another loop. It is useful when you want to iterate over multi-dimensional data structures like lists of lists (e.g., matrices).
for
Loop
# Example: Nested for loop
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for col in row:
print(col, end=" ")
print() # Adds a new line after each row
Output:
1 2 3
4 5 6
7 8 9
In this example:
for
loop iterates over the rows of the matrix (list of lists).for
loop iterates over each element (column) in a row.for
Loop with else
Python allows you to use an else
block with a for
loop. The else
block is executed when the loop completes normally (i.e., it doesn’t encounter a break
statement).
else
with a for
Loop
# Example: Using else with for loop
for i in range(3):
print(i)
else:
print("Loop completed without a break.")
Output:
0
1
2
Loop completed without a break.
In this case:
else
block runs after the loop has iterated over all elements.break
statement, the else
block will not execute.break
and continue
with for
LoopsYou can use the break
and continue
statements to control the flow of a for
loop.
break
: Terminates the loop early when a condition is met.continue
: Skips the current iteration and moves to the next iteration.break
to Exit the Loop
# Example: Using break in a for loop
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
In this example:
for
loop stops when i
reaches 5, due to the break
statement.continue
to Skip Iterations
# Example: Using continue in a for loop
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
Output:
1
3
5
7
9
Here:
continue
statement skips the even numbers and prints only the odd numbers.