How for loop in Python works internally?
Before proceeding to this section, you should have a prior understanding of Python Iterators.
Firstly, lets see how a simple for loops in Python looks like.
Example: This Python code iterates through a list called fruits
, containing “apple”, “orange” and “kiwi.” It prints each fruit name on a separate line, displaying them in the order they appear in the list.
fruits = ["apple", "orange", "kiwi"]
for fruit in fruits:
print(fruit)
Output
apple orange kiwi
Here we can see the for loops in Python that iterates over iterable object fruit which is a list. Lists, sets, dictionaries are few iterable objects while an integer object is not an iterable object. For loops can iterate over any of these iterable objects.
This Python code manually iterates through a list of fruits using an iterator. It prints each fruit’s name one by one and stops when there are no more items in the list.
fruits = ["apple", "orange", "kiwi"]
iter_obj = iter(fruits)
while True:
try:
fruit = next(iter_obj)
print(fruit)
except StopIteration:
break
Output
apple orange kiwi
We can see that under the hood we are calling iter() and next() method.
We have covered Python Loops in this article. We also saw how to use for loop, while loop and nested loop in Python. This article provides different use-case scenarios and examples to demonstrate working of loops and give clear understanding.
Learn More on Loops:
Loops in Python – For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp – For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time. In this article, we will look at Python loops and understand their working with the help of examples.