Introduction
In our last lesson, we focused on how to make your programs intelligent by using if/elif/else statements to make decisions. You learned how to execute different blocks of code based on specific conditions, which is a cornerstone of writing dynamic scripts.
Today, we're going to build on that by tackling a core concept of automation: repetition. This lesson addresses the learning outcome: to iterate over lists and other sequences using 'for' loops. While if statements let you handle a single piece of data, for loops empower you to apply logic to an entire collection of data—item by item—without writing the same code over and over. For your goal of building projects in data journalism, this is the mechanism you'll use to process every headline from a news site, analyze every word in an article, or organize rows of data for a report.
The Power of Iteration
At its core, a for loop is a way to say, "For each item in this collection, perform this action." It automates what would otherwise be a tedious, manual process.
Imagine you have a list of three strings: ["a", "b", "c"]. A for loop lets you take each one, in order, and do something with it. The image below shows the simplest form of a Python for loop. The code defines a list, and the loop then iterates through it, printing each item on a new line.

The general structure is:
for variable_name in sequence:
# Code to execute for each item
# This block must be indented
The Python Simplified channel has a great video that breaks down this concept. As you watch, pay close attention to the explanation of the iteration variable (like x in the image above) and the crucial role of indentation.
Python For Loops - Programming for Beginners
This video introduces the concept of for loops for iteration and walks through the syntax of looping over a list.
Watch from the beginning to the end of the first example. The host clearly explains the purpose of the loop, the iteration variable, the in keyword, and the indented body of the loop.
The "Pythonic" Way to Loop
If you have seen code from other languages (like Java, which you've used with BlueJ), you might have encountered loops that manually track an index, like for i = 0; i < length; i++. While you can do something similar in Python, it's not the recommended style. Python's for loop is designed to be more direct and readable. It's what programmers call "Pythonic."
The goal is to focus on the items in your list, not the numerical indices of those items. The following article from Python Morsels explains this important distinction.
Python's "for" loop - Python Morsels
This article explains the philosophy behind Python's for loop and why it's more readable and efficient to loop directly over items rather than indices.
Read the first section, Looping over an iterable, for a clear example. Then, read the next two sections, Looping using indexes, the wrong way and Python's for loops don't have (or need) indexes, to understand why the direct for fruit in fruits: style is preferred in Python.
Embracing this for-each style will make your code cleaner, more readable, and less prone to errors. It's a key habit to build as you become a Python programmer.
Combining Loops and Conditionals
The real power of loops emerges when you combine them with the conditional logic you learned in the last lesson. By placing an if statement inside a for loop, you can analyze every item in a list and act only on the ones that meet your criteria.
Let's imagine a scenario in data journalism. You have scraped a list of headlines and want to find all the ones related to a specific topic.
headlines = [
"Breaking News: Market Hits Record High",
"Local Elections See a Surprising Result",
"Tech Giant Unveils New Gadget for a lower price",
"Is the stock market going to crash?",
"Expert analysis of market trends"
]
search_term = "market"
print(f"Searching for headlines containing '{search_term}':\n")
# We create an empty list to store our findings
found_headlines = []
for headline in headlines:
# For each headline, check if the search term is present (case-insensitive)
if search_term in headline.lower():
# If it is, add the original headline to our list
found_headlines.append(headline)
# After the loop finishes, print the results
print("Found the following headlines:")
for found_headline in found_headlines:
print(f"- {found_headline}")
Try it yourself:
- Run the code above. It loops through the
headlines, checks each one, and uses a second loop at the end to print the filtered results. - Change the
search_termto "news" or "price" and see how the output changes. - Add a new headline to the initial
headlineslist and rerun the script.
This example brings together lists, for loops, the .lower() string method, and if statements—many of the core concepts we've covered so far. This pattern of iterating, checking, and collecting is fundamental to text analysis.
Using Loops to Build and Format Text
Another common use for loops is to construct a single string from a list of smaller strings. For instance, you might want to format a list of names into an HTML list or create a comma-separated string for a report.
The article from StrataScratch provides a clear example of this.
Python List Manipulation: Convert Lists to Strings - StrataScratch
This article discusses different ways to convert lists to strings. We will look at the sections that use a for loop for manual and formatted string building.
Read section "4. Using a For Loop – When You Want Full Control" to see how a loop can be used to manually build a string. Then, review section "5. Using F-Strings in a Loop – For Structured Formatting" to see how this can be combined with f-strings, a concept from our first lesson, to create more complex, structured output.
This technique is especially useful when preparing data for display on a webpage or in a text file, which are common tasks in web scraping and data journalism projects.
Conclusion
Today you've unlocked one of the most powerful tools in programming: the for loop. You now have the ability to automate tasks and apply complex logic to entire datasets, one item at a time.
Key takeaways from this lesson:
forloops are used to iterate over the items in a sequence, such as a list or a string.- The Pythonic way to loop is to iterate directly over the items (
for item in my_list), not by using indices. - You can nest
ifstatements insideforloops to selectively process items that meet certain criteria. - Loops are excellent for building new strings or lists from existing ones.
In our next lesson, we will learn how to define a Python function that accepts arguments and returns a value. Now that you can write powerful blocks of code that iterate and make decisions, the next logical step is to package that code into reusable, named blocks called functions. This will be the final piece of the puzzle before we start building more structured scripts and projects.