search

What is the difference between a normal for loop and a for-each loop in Python?

In Python, there is no separate "for-each" loop construct like in some other programming languages. The standard for loop in Python is often used as a "for-each" loop, iterating over the elements of an iterable object, such as a list, tuple, string, or generator.

The main difference between a "normal" for loop and a "for-each" loop in other languages is that the Python for loop automatically iterates over the elements of an iterable, rather than requiring manual indexing or iteration variables.

Here's an example to illustrate the usage of a "for-each" loop in Python using a for loop:

my_list = [1, 2, 3, 4, 5]

# Normal for loop
for item in my_list:
    print(item)

# Output: 1 2 3 4 5

In this example, the for loop iterates over each element of the my_list iterable, assigning each element to the item variable in each iteration. It automatically traverses the iterable and executes the loop body for each element, making it equivalent to a "for-each" loop.

The for loop in Python is designed to work efficiently with iterable objects and simplifies the process of iterating over their elements. It eliminates the need for manual indexing or maintaining loop counters, providing a clean and concise syntax for iteration.

It's worth noting that Python also provides additional looping constructs like while loops for general-purpose iteration and control flow. However, the standard for loop is commonly used for "for-each" style iteration over iterable objects.

Related Questions You Might Be Interested