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…