


Khusboo Tayal
Loops are essential for automating repetitive tasks. In Python, the for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) and perform operations on each item. This guide will walk you through how for loops work, how to use them effectively, and provide practical examples.
A for loop in Python is used to iterate over elements of a sequence one by one and perform a block of code for each element.
for item in sequence:
# code blockfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherryYou can also loop through the characters of a string:
for letter in "hello":
print(letter)Output:
h e l l o
The range() function generates a sequence of numbers, often used in for loops.
for i in range(5):
print(i)Output:
0 1 2 3 4
for i in range(1, 10, 2):
print(i)Output:
1 3 5 7 9
You can loop through keys, values, or both:
person = {"name": "Alice", "age": 25}
for key in person:
print(key, person[key])
Or:
for key, value in person.items():
print(key, value)You can use a for loop inside another for loop:
colors = ["red", "green"]
objects = ["car", "ball"]
for color in colors:
for obj in objects:
print(color, obj)break exits the loop early when a condition is met:
for num in range(10):
if num == 5:
break
print(num)continue skips the current iteration and moves to the next:
for num in range(5):
if num == 2:
continue
print(num)Python allows an optional else clause with loops. It runs when the loop completes without a break.
for i in range(3):
print(i)
else:
print("Loop completed!")
A compact way to create lists:
squares = [x**2 for x in range(5)] print(squares)
The for loop is a fundamental tool in Python programming. It's simple, powerful, and essential for performing repeated tasks over sequences. By mastering for loops, you’ll be able to write cleaner, more efficient Python code.
Q1: Can I modify a list while using a for loop?
Yes, but it's safer to loop over a copy to avoid unexpected behavior.
Q2: What's the difference between for and while loops?
for is used when the number of iterations is known, while is used when the condition is evaluated dynamically.
Q3: Can I use a for loop with sets and tuples?
Yes, for loops work with all iterable types, including sets and tuples.
Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythonforloops #pythonloops #learnpython #pythontutorial #pythonexamples #pythonbeginner #rangefunction #controlflow #iteration