Python, a versatile and beginner-friendly programming language, offers numerous control structures to manage the flow of programs. Among these, the ‘for’ loop stands out as a fundamental and widely used tool. It simplifies the task of iterating over sequences (such as lists, tuples, strings) or other iterable objects, making it easier to perform repetitive tasks or operations on each item in the sequence.
Basic Usage:
The basic syntax of a ‘for’ loop in Python is straightforward:
pythonCopy Codefor item in iterable:
# perform operations on item
Here, iterable
can be any sequence (like a list or a string) or an iterable object. The loop iterates over the iterable
, assigning each element to item
temporarily, and then executes the indented block of code for each item.
Example 1: Iterating Over a List
pythonCopy Codefruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This code snippet would print each fruit from the list on a new line.
Example 2: Using range()
Function
The range()
function is often used with ‘for’ loops to iterate a specific number of times.
pythonCopy Codefor i in range(5):
print(i)
This would print numbers from 0 to 4.
Nested Loops:
Python also allows for nested ‘for’ loops, which means one ‘for’ loop inside another ‘for’ loop.
pythonCopy Codeadj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for a in adj:
for f in fruits:
print(a, f)
This would print all possible combinations of adjectives and fruits.
Loop Control Statements:
Python provides loop control statements like break
and continue
to alter the flow of a ‘for’ loop. break
is used to exit the loop immediately, whereas continue
skips the rest of the code inside the loop for the current iteration only.
Example with break
:
pythonCopy Codefor i in range(10):
if i == 5:
break
print(i)
This would print numbers from 0 to 4.
Example with continue
:
pythonCopy Codefor i in range(10):
if i % 2 == 0:
continue
print(i)
This would print odd numbers from 0 to 9.
List Comprehensions:
‘for’ loops are also used in list comprehensions, which provide a concise way to create lists based on existing lists.
pythonCopy Codesquares = [x**2 for x in range(10)]
print(squares)
This would create and print a list of squares of numbers from 0 to 9.
Conclusion:
The ‘for’ loop in Python is a powerful tool for iterating over sequences and other iterable objects. Its simplicity and versatility make it an essential part of any Python programmer’s toolkit. Whether you’re processing data collections, generating new sequences, or controlling program flow, the ‘for’ loop is up to the task.
[tags]
Python, for loop, iterable, sequence, list comprehension, loop control statements