Python is a powerful programming language celebrated for its readability and simplicity. One of its core control structures is the for loop, which is essential for performing repetitive tasks over collections like lists, tuples, dictionaries, and strings. The for loop is versatile, efficient, and easy to implement, making it a crucial concept in Python programming. This comprehensive guide will walk you through everything you need to know about Python’s for loop, complete with examples, explanations, and real-world applications.
The for
loop in Python is used to iterate over a sequence (such as a list
, tuple
, dictionary
, or string
) and execute a block of code for each item in the sequence. Unlike the while
loop, the for
loop iterates through items in a collection rather than running based on a condition. It’s especially useful when the number of iterations is predetermined, such as looping through a list of elements.
for
LoopThe syntax of a for
loop is simple and easy to understand.
for item in sequence:
# Code to execute for each item
item
: The variable that takes the value of each element in the sequence on every iteration.sequence
: The collection (list
, tuple
, dictionary
, string
, etc.) that you are iterating over.for
Loop ExampleHere’s a basic example of a for
loop that iterates over a list of numbers and prints each one.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
1
2
3
4
5
for
loop iterates through each number in the numbers list.print(num)
statement executes for each element, printing each number.range()
with for
LoopThe range()
function is commonly used with for
loops to generate a sequence of numbers.
for i in range(start, stop, step):
# Code to execute
start
: Starting value (default is 0).stop
: End value (excluded from the range).step
: Increment between each value (default is 1).for i in range(1, 6):
print(i)
1
2
3
4
5
range(1, 6)
generates the numbers 1 through 5.for
loop iterates through this range, printing each value.Lists are a common data type to iterate over with for loops.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
Strings are iterable, so you can loop through each character.
word = "Python"
for char in word:
print(char)
P
y
t
h
o
n
Tuples are also iterable and work similarly to lists in for
loops.
colors = ("red", "green", "blue")
for color in colors:
print(color)
red
green
blue
Dictionaries can be looped through to access keys, values, or both.
Looping through keys:
student = {"name": "Alice", "age": 25, "grade": "A"}
for key in student:
print(key)
Output:
name
age
grade
Looping through values:
for value in student.values():
print(value)
Output:
Alice
25
A
Looping through key-value pairs:
for key, value in student.items():
print(f"{key}: {value}")
Output:
name: Alice
age: 25
grade: A
break
and continue
with for
Loopbreak
The break
statement exits the loop prematurely, even if items remain in the sequence.
for num in range(1, 6):
if num == 3:
break
print(num)
1
2
continue
The continue
statement skips the current iteration and moves to the next item in the sequence.
for num in range(1, 6):
if num == 3:
continue
print(num)
1
2
4
5
You can use a for
loop inside another for
loop, known as a nested loop.
for i in range(1, 4):
for j in range(1, 3):
print(f"i = {i}, j = {j}")
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
i
, the inner loop runs 2 times.else
with for
LoopAn else
block can be attached to a for
loop, which executes after the loop finishes all iterations, provided the loop wasn’t exited by a break
.
for num in range(1, 4):
print(num)
else:
print("Loop completed without break.")
1
2
3
Loop completed without break.
else
block executes after the loop completes all iterations.for
LoopList comprehension provides a concise way to create lists using for
loops.
new_list = [expression for item in iterable if condition]
squares = [x**2 for x in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]
Explanation:
for
loops, but can occur if using range()
incorrectly.Problem: Find all prime numbers between 1 and 10.
for num in range(2, 11):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)
2
3
5
7
Problem: Count the occurrences of each word in a sentence.
sentence = "this is a sample sentence with sample words"
word_counts = {}
for word in sentence.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
{'this': 1, 'is': 1, 'a': 1, 'sample': 2, 'sentence': 1, 'with': 1, 'words': 1}
Problem: Sum the values of all items in a dictionary.
prices = {"apple": 1.5, "banana": 0.8, "cherry": 2.0}
total_cost = sum(prices.values())
print(total_cost)
4.3
for
loops to iterate over sequences like lists, tuples, and strings.range()
is commonly used for generating numbers in loops.break
and continue
help control the flow within for
loops.for
loops.The for
loop is an essential tool in Python, allowing you to perform actions on each element in a sequence. Understanding for
loops enables you to write cleaner, more efficient code, whether you're iterating through lists, dictionaries, or other collections.
By mastering for loops, you can:
Practice these concepts, apply them in real projects, and see the versatility of Python’s for
loop in action.