Member-only story
In the world of programming, loops are a fundamental concept that allow you to automate repetitive tasks and perform operations on collections of data. Python, a versatile and beginner-friendly language, offers several types of loops, including the for loop.
In this article, we’ll dive into the intricacies of the for loop in Python, exploring its syntax, use cases, and providing practical examples to help you master this essential tool.
The Basics: Iterating Over Sequences
The for loop in Python is primarily used to iterate over sequences, such as lists, tuples, strings, or any other iterable object. Its basic syntax is as follows:
for item in sequence:
# code block to be executed
Here’s a simple example that prints each element of a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the for loop iterates over the fruits
list, and for each iteration, the current item (fruit
) is printed to the console.