A for
loop in Python is used to iterate over a sequence (like a list, tuple, string, or range). It allows you to execute a block of code repeatedly for each item in the sequence. Here’s a detailed explanation of the for
loop with a simple example.
Syntax
for item in sequence:
# Block of code to be executed for each item
item
: The variable that takes the value of the current element in the sequence during each iteration.sequence
: The sequence (like a list, tuple, string, or range) that you are iterating over.
Example 1: Iterating Through a List
Let’s use a simple example to illustrate a for
loop. We’ll iterate through a list of fruits and print each fruit.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the for
loop iterates through each item in the fruits
list. The fruit
variable takes the value of each item in the list during each iteration, and the print(fruit)
statement prints the current value of fruit
.
Example 2: Iterating Through a String
You can also use a for
loop to iterate through the characters in a string.
for char in "hello":
print(char)
Output:
h
e
l
l
o
In this example, the for
loop iterates through each character in the string "hello"
. The char
variable takes the value of each character during each iteration, and the print(char)
statement prints the current character.
Example 3: Using range()
The range()
function generates a sequence of numbers, which can be used to control the number of times a for
loop executes.
for i in range(5):
print(i)
Output:
0
1
2
3
4
In this example, the range(5)
function generates a sequence of numbers from 0 to 4. The for
loop iterates through these numbers, and the print(i)
statement prints the current value of i
.
Example 4: Iterating Through a Dictionary
You can also use a for
loop to iterate through the keys or key-value pairs of a dictionary.
person = {"name": "Alice", "age": 25, "city": "New York"}
# Iterating through keys
for key in person:
print(key)
# Iterating through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Output:
name
age
city
name: Alice
age: 25
city: New York
In this example, the first for
loop iterates through the keys of the person
dictionary and prints each key. The second for
loop uses the items()
method to iterate through the key-value pairs and prints each key along with its corresponding value.
Summary
for
loop: Used to iterate over a sequence (like a list, tuple, string, or range).- Syntax:
for item in sequence:
- Common Uses: Iterating through lists, strings, ranges, and dictionaries.