Member-only story

Python Tips — How “for loop” Work?

Tony
5 min readFeb 4, 2025

for ... in statement is probably the most used statement in Python programming. It is used to iterate over elements in container objects, which can be lists , tuples , dictionaries , sets , files , or even custom classes or functions, such as:

On list:

>>> for element in [1, 2, 3, 4]:
... print(element)
...
1
2
3
4

On tuples:

>>> for element in ("a", "b", 30):
... print(element)
...
a
b
30

On files:

>>> for line in open("requirement.txt"):
... print(line, end="")
...
Fabric==1.12.0
Markdown==2.6.7

You may ask why so many different types of objects support the for statement, and what other types of objects can be used in the for statement? Before answering this question, we need to understand the execution principle behind the for loop.

For Loop

A for loop is a process of iterating over a container, what is iteration? Iteration is reading elements one by one from a container object until there are no more elements in the container. So, which objects support iterative operations? Any object will do? First, try to customize a class and see if it works:

>>> class MyTest:
... def __init__(self, num):
... self.num = num
...
>>> for i…

--

--

Tony
Tony

Responses (1)