Learn Python
>>> control_flow.for_loop

for Loop in Python

#concept

A for loop repeats a block of code once for each item in a sequence — a string, a list, a range of numbers, or anything else Python can iterate over. Unlike loops in some languages that are built around a counter, Python's for loop is fundamentally about "do this for every item," with counting as just one common special case via range().

#how it works
1

for item in sequence:

Introduces the loop, choosing a name (item) for each element in turn.

2

Python takes the first element

And runs the indented block with item bound to it.

3

It repeats with the next element

And the next, until the sequence is exhausted.

4

The loop ends automatically

No explicit "increment and check" step is required.

5

range(n) is a common sequence to loop over

When you just need to repeat something n times.

#example
fruits = ["apple", "banana", "cherry"]
 
for fruit in fruits:
print(f"I like {fruit}")
 
for i in range(3):
print(i)
Output
I like apple
I like banana
I like cherry
0
1
2
1The first loop binds fruit to each element of fruits in turn — "apple", then "banana", then "cherry" — running print() each time.
2The loop ends automatically once every element has been used.
3range(3) produces the sequence 0, 1, 2 (three numbers, starting at 0), and the second loop prints each one.
#use cases
Processing every item in a list, like calculating a total or transforming each value
Repeating an action a fixed number of times with range()
Iterating over the characters of a string, or the keys of a dictionary
Reading every line of a file, one at a time

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.