In Python, the for
statement is a powerful and versatile construct used for iterating over sequences, collections, or any iterable object. It allows you to perform a specific set of actions for each item in the iterable, making it a fundamental tool for handling repetitive tasks efficiently. This tutorial will guide you through the various aspects of the for
statement in Python, along with illustrative examples to help you grasp its usage effectively.
Table of Contents
- Introduction to the
for
Statement - Basic Syntax of the
for
Statement - Iterating Through Lists
- Iterating Through Strings
- Iterating Through Dictionaries
- Nested
for
Loops - The
range()
Function and Numeric Iteration - Using the
enumerate()
Function - List Comprehensions with
for
Statements - Exiting Loops Prematurely with
break
- Skipping Iterations with
continue
- Practical Examples
- Example 1: Calculating the Sum of Numbers
- Example 2: Finding the Longest Word in a List of Strings
- Conclusion
1. Introduction to the for
Statement
The for
statement is one of the core control structures in Python that facilitates iterative processes. It allows you to iterate over a sequence of items, performing a set of actions for each item in the sequence. This sequence can be a list, tuple, string, dictionary, or any other iterable object.
2. Basic Syntax of the for
Statement
The basic syntax of the for
statement is as follows:
for item in iterable:
# Code to execute for each item
# ...
item
: This is a variable that takes the value of each item in the iterable during each iteration.iterable
: This is the collection of items over which the loop iterates.
3. Iterating Through Lists
One of the most common use cases for the for
statement is iterating through a list. Let’s see an example:
fruits = ['apple', 'banana', 'cherry', 'date']
for fruit in fruits:
print(f"I like {fruit}s")
Output:
I like apples
I like bananas
I like cherries
I like dates
4. Iterating Through Strings
Strings are iterable in Python, which means you can use a for
statement to iterate through each character in a string:
message = "Hello, Python!"
for char in message:
print(char)
Output:
H
e
l
l
o
,
P
y
t
o
n
!
5. Iterating Through Dictionaries
When iterating through dictionaries, the for
statement by default iterates through the keys. However, you can access both keys and values using the items()
method:
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
for student in student_grades:
print(f"{student} scored {student_grades[student]}")
# Using items() to iterate through keys and values
for student, grade in student_grades.items():
print(f"{student} scored {grade}")
Output:
Alice scored 85
Bob scored 92
Charlie scored 78
Alice scored 85
Bob scored 92
Charlie scored 78
6. Nested for
Loops
You can nest one or more for
loops within another for
loop to create more complex iterations. This is useful for iterating through multidimensional data structures like matrices or nested lists:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for num in row:
print(num, end=' ')
print() # Move to the next line after each row
Output:
1 2 3
4 5 6
7 8 9
7. The range()
Function and Numeric Iteration
The range()
function generates a sequence of numbers that can be used in for
loops. It can take one, two, or three arguments: range(stop)
, range(start, stop)
, or range(start, stop, step)
.
for i in range(5):
print(i)
for i in range(2, 10, 2):
print(i)
Output:
0
1
2
3
4
2
4
6
8
8. Using the enumerate()
Function
The enumerate()
function pairs each item in an iterable with its index. This is useful when you need both the index and the item during iteration:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"At index {index}: {fruit}")
Output:
At index 0: apple
At index 1: banana
At index 2: cherry
9. List Comprehensions with for
Statements
List comprehensions provide a concise way to create lists using for
statements. They allow you to generate new lists by applying an expression to each item in an existing iterable:
numbers = [1, 2, 3, 4, 5]
squared = [num ** 2 for num in numbers]
print(squared) # Output: [1, 4, 9, 16, 25]
10. Exiting Loops Prematurely with break
The break
statement is used to exit a loop prematurely based on a certain condition. It’s often used to terminate a loop when a specific value or condition is reached:
numbers = [10, 20, 30, 40, 50]
for num in numbers:
if num > 30:
break
print(num)
Output:
10
20
30
11. Skipping Iterations with continue
The continue
statement is used to skip the rest of the current iteration and proceed to the next one. It’s often used to exclude certain values from being processed within a loop:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
continue
print(num)
Output:
1
3
5
12. Practical Examples
Example 1: Calculating the Sum of Numbers
Let’s say you want to calculate the sum of numbers from 1 to 10 using a for
loop:
total = 0
for num in range(1, 11):
total += num
print("Sum:", total)
Output:
Sum: 55
Example 2: Finding the Longest Word in a List of Strings
You have a list of
words and you want to find the longest word:
words = ['apple', 'banana', 'cherry', 'date']
longest_word = ''
for word in words:
if len(word) > len(longest_word):
longest_word = word
print("Longest word:", longest_word)
Output:
Longest word: banana
13. Conclusion
In this tutorial, we explored the power and versatility of the for
statement in Python. We learned how to iterate through various types of iterables, work with nested loops, use the range()
function for numeric iteration, employ the enumerate()
function, and apply list comprehensions. Additionally, we saw how to control the flow of loops using the break
and continue
statements. Armed with this knowledge, you can now confidently use the for
statement to efficiently handle repetitive tasks in your Python programs. Happy coding!