10 Helpful Features to Use in a for Loop in Python
Just like other programming languages, we use for loops to perform repetitive work in Python. The most general form of a for loop takes the following format in Python:
for item in iterable:
# the operation goes here
We often use lists to store data in our project. We can use the list object in a for loop, as shown below.
fruits = ["pineapple", "banana", "grape"]
for fruit in fruits:
print(fruit)
Beyond the most common form, there are a variety of techniques that we can apply to a for loop, which allows us to write better iteration.
Without further ado, let’s get it started.
1. Enumerate Items with enumerate
In a for loop, sometimes you need to know the index of the item or the counter of the item in the iterable. For contrast, the following shows you a possible solution.
for item_i in range(len(fruits)):
fruit = fruits[item_i]
print(f"#{item_i+1}: {fruit}")#1: pineapple
#2: banana
#3: grape
However, a better way to implement this functionality is to use the built-in enumerate
function, which directly creates a counter together with the item of the iterable.
for item_i, fruit in enumerate(fruits, start=1):
print(f"#{item_i}: {fruit}")#1: pineapple
#2: banana
#3: grape
Note that I set the start
parameter to be 1 because I wanted the counter to start with 1. If you want, you can set a different starting value.
2. Reverse Items with reversed
Sometimes, you need to reverse the iterable for iteration. With a list object, you may use the reverse
function, which reverses the items of the list.
fruits.reverse()
for fruit in fruits:
print(fruit)grape
banana
pineapple
The same functionality can be easily accomplished with the reversed
function, as shown below. Please note that because we’ve reversed the list, when I use reversed
again…