How to Use for
in Python
In Python, the for
loop allows you to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. It is often used when you need to perform a certain task repeatedly for each item in the collection. Here’s a guide on how to use the for
loop in Python.
Basic Syntax
The basic syntax of a for
loop in Python is as follows:
python
for item in sequence:
# code block to be executed
item
: A temporary variable that represents the current item in the iteration.sequence
: The collection or iterable that the loop iterates over.
Iterating over a List
One common use case for the for
loop is iterating over a list of items. Here’s an example:
python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
In this example, the loop iterates over each item in the fruits
list, assigns the current item to the fruit
variable, and then executes the code block inside the loop (printing the fruit).
Range-based Iteration
The range()
function provides a convenient way to generate a sequence of numbers that can be used in a for
loop. Here’s an example:
python
for i in range(5):
print(i)
Output:
0
1
2
3
4
In this case, the loop iterates over a sequence of numbers generated by range(5)
(0 to 4). The current number is assigned to the i
variable, and the code block inside the loop is executed.
Iterating over a String
You can also use a for
loop to iterate over individual characters in a string. Here’s an example:
python
message = "Hello, World!"
for char in message:
print(char)
Output:
“`
H
e
l
l
o
,
W
o
r
l
d
!
“`
In this example, the loop iterates over each character in the message
string, assigns the current character to the char
variable, and prints it.
enumerate()
for Index-based Iteration
Sometimes, you might need to access both the index and value of each item in a sequence. The enumerate()
function can be used to achieve this. Here’s an example:
python
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Color {index+1}: {color}")
Output:
Color 1: red
Color 2: green
Color 3: blue
In this case, the enumerate()
function generates pairs of (index, value)
for each item in colors
, and the for
loop assigns them to the index
and color
variables. The code block inside the loop then prints the index and corresponding color.
These are the basics of using the for
loop in Python. With its flexibility and simplicity, the for
loop is a powerful construct for iterating over collections and performing repetitive tasks.