- Python Snacks
- Posts
- A quick tutorial for the for/else construct in Python
A quick tutorial for the for/else construct in Python
Here's how you're able to use this and why sometimes it's more adventageous
In a Python course, you learned that you use an else statement when you use an if statement:
if condition:
# Do stuff
else:
# Do stuff given condition failed
But, you can also use the else statement in conjunction with a for loop, which allows you to signify that a loop was never broken out of with a break statement:
items = ['apple', 'banana', 'cherry', 'date']
search_item = 'orange'
for item in items:
if item == search_item:
print(f"Found {search_item}!")
break
else:
print(f"{search_item} not found in the list.")
How for/else works
The else block in a for/else loop is executed only if the loop completes all its iterations without encountering a break statement. If the loop is interrupted by a break statement, the else block is skipped.
In the code snippet above, we search for the word “orange” in the items list. If we find it, we print a success message and exit the loop with break.
However, if the loop completes without finding “orange”, the else block runs, printing a message that the item was not found.
The purpose of for/else
Going back to the semi-early days of your Python learning, you learned about control flow. This was referring to looping (for/while) and if/elif/else statements.
However, this construct was likely left out for a number of reasons:
It’s an unconventional way to write Python code,
This construct is not found in any other languages,
There’s very limited use cases.
Key usage: Use a for/else loop to define behavior after you are done looping if you don’t break out of the loop.
Copy/pasting the code from above for reference:
items = ['apple', 'banana', 'cherry', 'date']
search_item = 'orange'
for item in items:
if item == search_item:
print(f"Found {search_item}!")
break
else:
print(f"{search_item} not found in the list.")
We want to find the word orange in the items list above. If we successfully find this, then we’ll print out a success message and break out of the loop.
However, if we’re unsuccessful in finding the word orange in the list, then we’ll execute the else statement, saying we didn’t find it.
Another Way to Write the Code
Instead of using a for/else statement, we could stick with an if/else statement outside of the for loop. We’d have to include a boolean to keep track of whether we found the item or not:
items = ['apple', 'banana', 'cherry', 'date']
search_item = 'orange'
item_found = False # assume it hasn't been found
for item in items:
if item == search_item:
item_found = True
break
if item_found:
print(f"Found {search_item}!")
else:
print(f"{search_item} not found in the list.")
Both constructs that are shown here are valid ways of writing code. This way is more straight-forward and forces us to think in a more logical manner.
At the end of the day, it’s up to you how you want to handle something like this. I think that the for/else statement is slightly more elegant, as we don’t need to have another variable introduced in our code.
📧Join the Python Snacks Newsletter!🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply