Python for Data Analytics • Lesson 13

for Loops

Learn how to repeat code efficiently using Python for loops. Work with sequences, range(), lists, strings, and real data analysis examples.

Your progress0%

0 of 8 concepts completed

Complete the activity and related MCQ to unlock the next concept.

Concept 1WHY LOOPS

Why Do We Need Loops?

A loop lets Python repeat a block of code without you writing it out again and again. Without loops, printing 1 to 5 means five separate print() lines.

Learn by Seeing

Repeat automatically

# Without a loop
print(1)
print(2)
print(3)

# With a loop
for number in range(1, 4):
    print(number)

One loop replaces a long list of repeated instructions.

Compare manually written lines vs one loop:

Without a loop

print(1)
print(2)
print(3)
print(4)
print(5)

With a loop

for i in range(1, 6):
    print(i)

Interactive Activity

How many print() lines are needed to print 1 to 5 WITHOUT a loop?

Hint: One line per number.

Python Analyst Mindset

Loops are how you touch every row

Whether you are filtering a DataFrame, processing a file line by line, or applying a business rule to every transaction, you are looping. for is the analyst's way of saying "do this to each of these".

01

Repeat

One loop replaces many lines.

02

Sequence

Visit each item in a list or string.

03

Count

Use an accumulator with a loop.

04

Filter

Combine with if for conditional logic.

Frequently Asked Questions

for Loops — FAQs

Why does range(5) stop at 4?

range() is designed to exclude the stop value, so the number of items matches the argument. range(5) gives exactly 5 numbers, 0 through 4.

Can I skip the colon?

No. Every for (and if, while, def) statement must end with a colon and an indented body.

How do I loop through numbers in reverse?

Use a negative step: range(10, 0, -2) gives 10, 8, 6, 4, 2.

Can I modify a list while looping over it?

Not safely. Build a new list, or loop over a copy. Modifying during iteration gives unpredictable results.

Lesson Summary

What you learned

for loop

Repeats code once per item.

range(n)

0 up to (but not including) n.

range(start, stop)

Starts at start, excludes stop.

range(start, stop, step)

Advance by step each iteration.

Lists and strings

Walk either as a sequence.

Loop + if

Count or filter high-value records.