Python for Loops: The Pythonic Way :
by:
blow post content copied from Real Python
click here to view original post
Python’s for
loop allows you to iterate over the items in a collection, such as lists, tuples, strings, and dictionaries. The for
loop syntax declares a loop variable that takes each item from the collection in each iteration. This loop is ideal for repeatedly executing a block of code on each item in the collection. You can also tweak for
loops further with features like break
, continue
, and else
.
By the end of this tutorial, you’ll understand that:
- Python’s
for
loop iterates over items in a data collection, allowing you to execute code for each item. - To iterate from
0
to10
, you use thefor index in range(11):
construct. - To repeat code a number of times without processing the data of an iterable, use the
for _ in range(times):
construct. - To do index-based iteration, you can use
for index, value in enumerate(iterable):
to access both index and item.
In this tutorial, you’ll gain practical knowledge of using for
loops to traverse various collections and learn Pythonic looping techniques. Additionally, you’ll learn how to handle exceptions and how to use asynchronous iterations to make your Python code more robust and efficient.
Get Your Code: Click here to download the free sample code that shows you how to use for loops in Python.
Take the Quiz: Test your knowledge with our interactive “The Python for Loop” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
The Python for LoopIn this quiz, you'll test your understanding of Python's for loop and the concepts of definite iteration, iterables, and iterators. With this knowledge, you'll be able to perform repetitive tasks in Python more efficiently.
Getting Started With the Python for
Loop
In programming, loops are control flow statements that allow you to repeat a given set of operations a number of times. In practice, you’ll find two main types of loops:
for
loops are mostly used to iterate a known number of times, which is common when you’re processing data collections with a specific number of data items.while
loops are commonly used to iterate an unknown number of times, which is useful when the number of iterations depends on a given condition.
Python has both of these loops and in this tutorial, you’ll learn about for
loops. In Python, you’ll generally use for
loops when you need to iterate over the items in a data collection. This type of loop lets you traverse different data collections and run a specific group of statements on or with each item in the input collection.
In Python, for
loops are compound statements with a header and a code block that runs a predefined number of times. The basic syntax of a for
loop is shown below:
for variable in iterable:
<body>
In this syntax, variable
is the loop variable. In each iteration, this variable takes the value of the current item in iterable
, which represents the data collection you need to iterate over. The loop body can consist of one or more statements that must be indented properly.
Here’s a more detailed breakdown of this syntax:
for
is the keyword that initiates the loop header.variable
is a variable that holds the current item in the input iterable.in
is a keyword that connects the loop variable with the iterable.iterable
is a data collection that can be iterated over.<body>
consists of one or more statements to execute in each iteration.
Here’s a quick example of how you can use a for
loop to iterate over a list:
>>> colors = ["red", "green", "blue", "yellow"]
>>> for color in colors:
... print(color)
...
red
green
blue
yellow
In this example, color
is the loop variable, while the colors
list is the target collection. Each time through the loop, color
takes on a successive item from colors
. In this loop, the body consists of a call to print()
that displays the value on the screen. This loop runs once for each item in the target iterable. The way the code above is written is the Pythonic way to write it.
However, what’s an iterable anyway? In Python, an iterable is an object—often a data collection—that can be iterated over. Common examples of iterables in Python include lists, tuples, strings, dictionaries, and sets, which are all built-in data types. You can also have custom classes that support iteration.
Note: Python has both iterables and iterators. Iterables support the iterable protocol consisting of the .__iter__()
special method. Similarly, iterators support the iterator protocol that’s based on the .__iter__()
and .__next__()
special methods.
Both iterables and iterators can be iterated over. All iterators are iterables, but not all iterables are iterators. Python iterators play a fundamental role in for
loops because they drive the iteration process.
A deeper discussion on iterables and iterators is beyond the scope of this tutorial. However, to learn more about them, check out the Iterators and Iterables in Python: Run Efficient Iterations tutorial.
You can also have a loop with multiple loop variables:
>>> points = [(1, 4), (3, 6), (7, 3)]
>>> for x, y in points:
... print(f"{x = } and {y = }")
...
x = 1 and y = 4
x = 3 and y = 6
x = 7 and y = 3
In this loop, you have two loop variables, x
and y
. Note that to use this syntax, you just need to provide a tuple of loop variables. Also, you can have as many loop variables as you need as long as you have the correct number of items to unpack into them. You’ll also find this pattern useful when iterating over dictionary items or when you need to do parallel iteration.
Sometimes, the input iterable may be empty. In that case, the loop will run its header once but won’t execute its body:
>>> for item in []:
... print(item)
...
Read the full article at https://realpython.com/python-for-loop/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
February 03, 2025 at 07:30PM
Click here for more details...
=============================
The original post is available in Real Python by
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment