Python for loop
The for
loop in Python is used to iterate over a sequence (like a list, tuple, string, dictionary, or range) and execute a block of code repeatedly for each element in that sequence. Here’s a detailed explanation of how it works and its key features:
Syntax of a for
loop
for variable in sequence:
# Code block to execute
Components:
for
: The keyword that initiates the iteration.variable
: The placeholder where at the present iteration the value of each object in the sequence is inserted.in
: The keyword associating variable with the sequence.sequence
: An iterable object like list, range, tuple, string, dictionary or set.- Code block: An indented block of code that gets executed for every iteration.
How It Works
- The loop takes one element out of the sequence and assigns that to the variable.
- The code block is run with the value of the variable at present.
- This process continues until all the elements in the sequence have been traversed.
Examples
- Iterating Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. Using range( )
in a for
loop
for i in range(5):
print(i)
Output:
0
1
2
3
4
Here, range(5)
will generate numbers from 0 to 4.
3. Iterating Through a String
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
4. Iterating Through a Dictionary
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(key, ":", value)
Output:
name : Alice
age : 25
Common Features
break
Statement
Stops the loop prematurely when a condition is met.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
2. continue
Statement
Skips the current iteration and proceeds to the next.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
3. else
Clause
Executes after the loop completes normally (i.e., without a break).
for i in range(3):
print(i)
else:
print("Loop completed")
Output:
0
1
2
Loop completed
Iterating Over Complex Structures
- Nested Loops
You can use loops inside loops to work with multidimensional data.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for value in row:
print(value, end=" ")
Output:
1 2 3 4 5 6 7 8 9
2. Enumerate
Returns both index and value during iteration.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
3. Zip
Combines two or more sequences for iteration.
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(name, "is", age, "years old")
Output:
Alice is 25 years old
Bob is 30 years old
Summary:
- Efficient: Iterates directly over items without needing indices.
- Flexible: Works with any iterable (lists, tuples, strings, etc.).
- Customizable: Use
break
,continue
,else
,enumerate
, orzip
for advanced functionality.