There are a variety of ways of using For loop in Python. In this blog post, we will walkthrough different methods of writing For loops in Python.
We'll understand usage of following functions for writing For loops in Python
range(start, stop, increment)
enumerate(iterable, start=0)
Let's dive right into the code to understand this.
Consider following list
of cars.
cars = ['kia', 'audi', 'bmw']
Iterating each object in a list.
This is the most basic form of for loop.
Example:
for car in cars:
print(car)
Iterating using an index and inbuilt range
function in Python.
Example
for i in range(len(cars))
print(cars[i])
Iterating using enumerate
keyword.
The enumerate() method adds counter to an iterable and returns it (the enumerate object).
Example:
for i, car in enumerate(cars):
print("Index - {} Car - {}".format(i, car))
When is it useful?
Usage of enumerate
makes the code cleaner. We would have otherwise used range(len(cars))
to iterate over the list.
If we do not need the index i
, we can very well replace it with _
as a placeholder.
Example:
for _, car in enumerate(cars):
print("Car - {}".format(car))
These were some of the ways of writing For loops in Python.