In one of my previous articles we were talking about iterating over ranges. Today we’ll learn how to use the range function to iterate over the indices of a sequence.
You can use the range function if you want to iterate over the indices of a sequence. All you have to do is pass the length of the sequence as the argument to the range function:
cars = ["Porsche", "Chevrolet", "Peugeot", "Honda"]
for index in range(len(cars)):
print(cars[index] + " is at index " + str(index) + ".")
And here’s the output:
Porsche is at index 0.
Chevrolet is at index 1.
Peugeot is at index 2.
Honda is at index 3.
Here the length of the list is 4 and range(4) generates the numbers 0, 1, 2 and 3, which are the indices in the list.