In programming, we frequently encounter situations where we want to apply the same process sequentially to a collection of data (such as a list or tuple). Python allows you to write these repetitive tasks concisely using the for statement.
Python’s for loop is different from the “counter-based” style found in other languages (like for i = 0; i < 10; i++). Instead, it has an intuitive and powerful mechanism that “extracts elements one by one from a collection (iterable) and processes them.”
This article explains the basic syntax of the for statement and how to loop through iterables like lists.
Basic Syntax of the for Statement
Python’s for statement is written with the following syntax:
for variable in iterable:
# Write the process to repeat here
# The element extracted from the iterable is assigned to the variable
An Iterable is a general term for objects from which elements can be extracted in order, such as lists, tuples, strings, dictionaries, and sets.
1. Looping Through a List
The most common usage is to perform operations on each element contained in a list. In the following example, we extract server names from a list one by one and perform a connection process (simulated by printing a message).
# List of server names
server_list = ["Web-Server-01", "DB-Server-01", "Cache-Server-01"]
print("--- Maintenance Start ---")
# Assign list elements to the 'server' variable one by one and loop
for server in server_list:
print(f"Connecting: {server}")
print(f"Backup created for {server}.")
print("--- Maintenance End ---")
Output:
--- Maintenance Start ---
Connecting: Web-Server-01
Backup created for Web-Server-01.
Connecting: DB-Server-01
Backup created for DB-Server-01.
Connecting: Cache-Server-01
Backup created for Cache-Server-01.
--- Maintenance End ---
2. Aggregating Numeric Lists
Here is an example of looping through a list of numbers to calculate the total value.
# Daily sales data
daily_sales = [1500, 2300, 1800, 3200, 2100]
total_sales = 0
for sale in daily_sales:
# Add sales
total_sales += sale
print(f"Number of data points: {len(daily_sales)}")
print(f"Total Sales: {total_sales}")
Output:
Number of data points: 5
Total Sales: 10900
3. Looping Through Strings
In Python, a string (str) is also a type of iterable. If you pass a string to a for statement, it extracts one character at a time.
app_code = "A105"
print("Code Analysis:")
for char in app_code:
# Check if the character is a digit and display
if char.isdigit():
print(f"Digit: {char}")
else:
print(f"Char: {char}")
Output:
Code Analysis:
Char: A
Digit: 1
Digit: 0
Digit: 5
Summary
- Python’s
forstatement is written in the format:for variable in iterable:. - It extracts elements sequentially from lists, tuples, strings, etc., and executes the process in the block.
- Because you can operate directly on the elements without worrying about index numbers (0, 1, 2…), you can write highly readable code.
