For Loop in Python
In Python, the for
loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. Here's the basic syntax of a For
loop in Python:
pythonCopy codefor item in iterable:
# Code block to execute for each iteration
# You can use the 'item' variable to access the current element
# of the iterable
Here's a breakdown of how it works:
item
: This is a variable name that represents the current element in the iteration. You can choose any valid variable name here.iterable
: This is the object over which the loop iterates. It could be a list, tuple, string, dictionary, or any other iterable object.Indentation: In Python, indentation is crucial for defining blocks of code. The code block following the
for
statement is indented, typically by four spaces (or a tab), to indicate that it belongs to the loop.
Example 1: Iterating over a list:
pythonCopy codefruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Iterating over a string:
pythonCopy codefor char in "hello":
print(char)
Output:
h
e
l
l
o
Example 3: Using range()
for a numerical loop:
pythonCopy codefor i in range(5):
print(i)
Output:
0
1
2
3
4
In this last example, range(5)
generates numbers from 0 to 4, and the loop iterates over these numbers, assigning each to the variable i
.
Remember, the for
loop can be used with any iterable object in Python, making it a versatile tool for iteration. Learn more with programs such as masters in data Science and free python tutorial online!
Subscribe to my newsletter
Read articles from Anuradha Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by