Python For Loop
The for
loop in Python is one of the most commonly used loops. It is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code multiple times.
What is a For Loop?
A for
loop is used to iterate over a sequence of items. Each time, the loop takes one element from the sequence and assigns it to the loop variable, which is used inside the loop body.
The syntax of a for
loop is:
Syntax of For Loop
Syntax
for variable in sequence:
# Code block to execute
Explanation:
In this syntax:variable
: This is the loop variable that takes the value of each item in the sequence during each iteration.sequence
: This can be any iterable object like a list, tuple, string, or a range.- The code block inside the loop runs once for each item in the sequence.
Example :1
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output
for
loop iterates over the list fruits
. Each time, the loop takes one element (fruit) from the list and prints it.
Using For Loop with Range
The range()
function is often used with for
loops when you want to iterate over a sequence of numbers. The range()
function generates a sequence of numbers starting from the first number to the second number (excluding the second number).
Syntax of Range
Syntax
range(start, stop, step)
Explanation:
In therange()
function:
start
: The starting number of the sequence (optional, default is 0).stop
: The end number (exclusive) where the sequence stops.step
: The increment step (optional, default is 1).
Example :2
for i in range(1, 6):
print(i)
Output
range(1, 6)
generates numbers from 1 to 5, and the loop prints each number.
Nested For Loops
It’s also possible to use one for
loop inside another, which is known as a "nested for loop". This is helpful when dealing with multi-dimensional data, like lists of lists.
Syntax of Nested For Loops
Syntax
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Code block to execute
Example :3
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element)
Output
for
loop iterates over each row of the matrix (which is a list of lists), and the inner for
loop iterates over the elements of each row.
Best Practices
- Use meaningful variable names: Make your loop variable names clear and descriptive, like
item
,element
, ornum
. - Keep code inside the loop efficient: Try to minimize the number of operations inside a loop to improve performance.