Skip to main content

Command Palette

Search for a command to run...

Python's For Loop Made the Counter Variable Disappear (Here's How)

Updated
3 min readView as Markdown
 Python's For Loop Made the Counter Variable Disappear (Here's How)
D

A dedicated Computer Engineering graduate from SCET. Throughout my academic journey, I navigated the dynamic landscape of education during the challenging Covid era, which instilled in me resilience and adaptability. My experience in the field of Data Engineering spans across Transact SQL, MS SQL Server, Agile Methodologies, and a foundational understanding of Azure Data Factory and various cloud services. These experiences have not only honed my technical acumen but also reinforced my capacity to thrive in diverse and evolving environments.

My current pursuits reflect a keen interest in expanding my knowledge in both DevOps and Cloud Engineering. Alongside these technical endeavors, I'm fervently learning Full Stack Web Development from the ground up, eager to explore the intricate interplay of front-end and back-end systems.

Embracing a holistic approach to problem-solving, I'm delving into the intricacies of System Design, striving to develop comprehensive and efficient solutions within the IT industry. Building on approximately 6 months to 1-year of hands-on industry experience, I'm driven to continuously enhance my skill set, contributing meaningfully to the technological landscape.

Beyond the realms of technology, I find solace in capturing the ephemeral beauty of sunsets through photography, letting the time freeze those breathtaking moments. Music is my constant companion, offering relaxation and inspiration. As an avid cricket enthusiast, the game brings camaraderie and excitement.

I'm always open to connecting with fellow professionals, learning from shared experiences, and contributing to the ever-evolving tech sphere. Let's connect and explore the limitless possibilities together!

With a while loop, I had to manually create a counter, check it, and update it every single time. Python's for loop handles that bookkeeping for you.

The basic syntax

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

range(1, 11) generates the numbers 1 through 10, one at a time, each getting assigned to i for that pass through the loop. Same rule as everywhere else in Python: the upper bound is excluded, which is why it's 11 and not 10 to actually reach ten.

It's not just for numbers

This is the part that actually surprised me. A for loop can iterate over pretty much any collection of values, not just a range of numbers.

for letter in "Darshan":
    print(letter)
# prints D, a, r, s, h, a, n, one per line
numbers = [10, 20, 30]
for n in numbers:
    print(n)

coordinates = (1, 2, 3)
for c in coordinates:
    print(c)

Lists and tuples are getting their own dedicated posts later in this series, so I'm not going deep on them here, but it's worth knowing now that for loops work with them the same natural way they work with strings and ranges.

Controlling the step

range() actually takes a third value: a step, controlling how much it increments each time.

for i in range(1, 10, 2):
    print(i)   # 1, 3, 5, 7, 9

for i in range(1, 10, 3):
    print(i)   # 1, 4, 7

You can also go backward with a negative step:

for i in range(10, 0, -1):
    print(i)   # 10, 9, 8, ..., 1

Rewriting the print-10-times task

Just to compare directly against the while loop version from the last post:

for i in range(1, 11):
    print("Darshan")

No manual counter, no manual increment. The range() object handles all of that internally.

Exercise: population decline over the last 10 years

Say a town's current population is 10,000, and it's been growing 10% per year. Working backward, what was the population in each of the last ten years?

current_population = 10000

for i in range(10, 0, -1):
    print(i, current_population)
    current_population = current_population / 1.1

The reverse range (10, 0, -1) walks backward year by year, and dividing by 1.1 each time undoes one year's 10% growth, working from the present back toward the past.

Common mistakes I'd flag here

  • Forgetting range()'s upper bound is exclusive, the same trap as while loop conditions, just in a new shape.

  • Getting the step direction wrong. range(10, 0, -1) needs a negative step to count downward, a positive step there produces an empty range instead of an error, which can be a confusing silent failure.

  • Assuming for loops only work on numbers, and missing that strings, lists, and tuples all iterate naturally too.

Quick recap

  • for i in range(start, stop) loops over a sequence of numbers, with stop excluded, and handles the counter automatically.

  • for loops work over strings, lists, and tuples directly, not just number ranges.

  • range()'s optional third argument sets the step size, and a negative step counts backward.

  • Combining a reverse range with a formula was enough to reconstruct a decade of population history in four lines.

What's next

Next up: nested for loops, and why you'd ever want a loop inside another loop.

Bite-Sized Python: Zero to Modular Code

Part 9 of 15

Learning to code or pivoting into modern software development can feel like wading through an ocean of tutorials. In this series, I document my hands-on journey through Python, breaking down every core concept into plain-English explanations, visual mental models, and ready-to-use code snippets. Whether you are writing your first print() statement or learning how to structure production-ready modular applications, follow along as we build our skills one post at a time.

Up next

Nested For Loops Finally Made Sense Once I Saw Amazon's Category Pages

Browse Amazon's category menu: click "Computers," and a whole set of subcategories appears. Click "Laptop Accessories," and now you're seeing individual products. That's two loops working together: on

More from this blog

The Accidental Techie: Darshan Joshi

19 posts

Code creator by day, deep thinker by night✨ weaving bytes and pondering life's algorithms❤

A dedicated Computer Engineering graduate from SCET. Throughout my academic journey, I navigated the dynamic landscape of education during the challenging Covid era, which instilled in me resilience and adaptability. My experience in the field of Data Engineering spans across Transact SQL, MS SQL Server, Agile Methodologies, and a foundational understanding of Azure Data Factory and various cloud services. These experiences have not only honed my technical acumen but also reinforced my capacity to thrive in diverse and evolving environments.

My current pursuits reflect a keen interest in expanding my knowledge in both DevOps and Cloud Engineering. Alongside these technical endeavors, I'm fervently learning Full Stack Web Development from the ground up, eager to explore the intricate interplay of front-end and back-end systems.

Embracing a holistic approach to problem-solving, I'm delving into the intricacies of System Design, striving to develop comprehensive and efficient solutions within the IT industry. Building on approximately 6 months to 1-year of hands-on industry experience, I'm driven to continuously enhance my skill set, contributing meaningfully to the technological landscape.

Beyond the realms of technology, I find solace in capturing the ephemeral beauty of sunsets through photography, letting the time freeze those breathtaking moments. Music is my constant companion, offering relaxation and inspiration. As an avid cricket enthusiast, the game brings camaraderie and excitement.

I'm always open to connecting with fellow professionals, learning from shared experiences, and contributing to the ever-evolving tech sphere. Let's connect and explore the limitless possibilities together!