For Loops in Python#
š Data Analysis Using Python š Control Flow Lesson 014
ā Previous Ā· Next ā¶ Ā· ā Section Ā· ā Hub
Important
⨠AI-generated content. This page was written with the assistance of an AI language model and is provided as a learning aid. Despite careful review, it may still contain mistakes, omissions, or out-of-date information. Whether you are new to the topic, a team lead, or a senior practitioner, treat it as a starting point rather than an authoritative reference: read it critically and independently verify anything you act on (code, commands, figures, and factual claims) against official documentation and primary sources before relying on it.
Repeating over a collection#
When you need to do something for each item in a collection, the for loop is the natural tool ā it iterates over the items of a sequence, running its block once per item. This is the loop analysts use most, because data work is largely ādo this to every row, value, or record.ā This lesson covers the for loop, the workhorse of iteration.
The for loop#
A for loop iterates over the items of a collection, binding each to a variable in
turn:
regions = ["North", "South", "East", "West"]
for region in regions:
print(region)
Python takes each item of regions in order, assigns it to region, and runs the
block ā printing all four region names. The loop variable (region) holds the current
item on each pass. Unlike the while loop, the for loop automatically stops when the
collection is exhausted ā no manual progress-tracking, and no risk of an infinite loop
over a finite collection.
Iterating and accumulating#
A common pattern combines a for loop with a variable that accumulates a result across iterations:
sales = [100, 250, 175, 300]
total = 0
for amount in sales:
total += amount # accumulate
print(total) # 825
The total starts at zero and grows by each amount as the loop visits it ā computing a
sum by iteration. This accumulate-across-a-loop pattern (summing, counting, collecting,
building) is one of the most useful in programming, and it is how manual aggregation is
expressed in code (though pandas, later, does it far more concisely).
For loops over different collections#
For loops iterate any iterable ā lists, strings (character by character), dictionaries (the structures stage), and more:
for char in "data": # iterates characters: d, a, t, a
print(char)
This generality makes the for loop the standard way to process collections of any kind ā whatever the data, āfor each item, do somethingā is a for loop.
The caveat#
For loops are safer than while loops (they cannot loop infinitely over a finite
collection), but they have their own pitfalls. Modifying a collection while iterating
over it causes subtle bugs (the collection changes underfoot) and should be avoided ā
build a new collection instead. And a deeper point looms for data work: explicit Python
for loops over large datasets are slow compared to the vectorised operations of
numpy and pandas (the libraries stage), which do the same work far faster without
an explicit loop. Loops are essential to understand and correct for general programming,
but for large-scale data the idiom shifts to vectorised operations ā a for loop over a
million-row dataset is usually the wrong tool. Learn loops thoroughly, and later learn
when not to loop. The next lesson covers generating sequences and controlling loops.
Hint
See also
Source article Adapted (context, re-expressed) in our own words from: https://insightful-data-lab.com/2023/12/06/for-loops-in-python/ (insightful-data-lab.com).