Blog Post #34: The Most Pythonic Loop: Introducing the for Loop

In our previous posts, we learned about the while loop. It’s a fantastic tool for repeating a block of code as long as a condition is true, especially when we don’t know how many repetitions we’ll need, like in our menu project from Post #33.

But what if our goal is different? What if we want to perform an action for each item in a collection? For example, printing every character in a word, or processing every item in a shopping list. For these tasks, Python provides a more elegant, suitable, and common tool.

In this post, we will explore the for loop, which is the most “Pythonic” way to iterate over sequences.

Iterating Over a Sequence

The core idea of a for loop is to iterate over a sequence. An “iterable” is anything that can be looped over—a collection of items. The simplest iterable we’ve worked with so far is a string, which is a sequence of characters. Another common iterable is a list, which is a collection of items stored in square brackets.

A for loop will run once for every single item in the sequence, automatically stopping when it reaches the end.

The for Loop Syntax

The syntax is very readable and straightforward.

for temporary_variable in iterable:
    # Code to execute for each item

Let’s break this down:

  • for and in are keywords that make up the loop structure.
  • iterable: This is the collection you want to loop through (e.g., a string variable or a list).
  • temporary_variable: This is a new variable that you name. On the first pass of the loop, Python automatically assigns the first item from the iterable to this variable. On the second pass, it gets the second item, and so on, until the iterable is exhausted.

for Loops in Action

Let’s see this with a couple of clear examples.

Example 1: Looping Through a String

A string is a sequence of characters, so a for loop is a perfect way to process it character by character.

word = "Python"

for character in word:
    print(character)

When this code runs, here’s what happens:

  1. Python starts the for loop on the word “Python”.
  2. On the first pass, it assigns the first character, "P", to the character variable and runs the loop body, printing “P”.
  3. On the second pass, it assigns "y" to character and prints it.
  4. This continues until the last character, "n", is printed. The loop then automatically stops.

The output will be:

P
y
t
h
o
n

Example 2: Looping Through a List

While we will cover lists in detail in Part 3, let’s look at a quick example to see the versatility of for loops. A list is just a collection of items separated by commas inside square brackets.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I would like to eat a {fruit}.")

The output will be:

I would like to eat a apple.
I would like to eat a banana.
I would like to eat a cherry.

As you can see, the fruit variable holds a different value from the list on each iteration.

Why for Loops are Pythonic

To truly appreciate the simplicity of the for loop, let’s see how we would have to loop through a string using a while loop.

# The 'while' loop way (more complex)
word = "Python"
index = 0

while index < len(word):
    print(word[index])
    index += 1

This while loop is much more work! We have to manually initialize an index, check the length of the string, access the character using word[index], and most importantly, remember to increment the index. It’s easy to make a mistake.

The for loop handles all of that bookkeeping for you. It’s more readable, less prone to errors, and is the clear choice when you want to iterate over a sequence. This is a perfect example of what it means to write “Pythonic” code.

What’s Next?

You’ve now learned about the for loop, Python’s primary tool for iterating over sequences like strings and lists. It provides a clean and readable way to perform an action on every item in a collection.

Looping through existing sequences is very powerful, but what if you just want to repeat a block of code a specific number of times, like 10 times or 100 times? The for loop has a perfect companion for this task. In Post #35, we will explore the range() function, a tool for generating sequences of numbers on demand to control our loops.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment