Python For Loop Increment in Steps
To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the “loop index” in required amount of steps.
In this tutorial, we will learn how to loop in steps, through a collection like list, tuple, etc. This would be like hopping over the collection
Python For Loop Increment by 2
In the following example, we will use range() function to iterate over the elements of list using Python For Loop in steps of 2.
Example.py
list_1 = [9, 5, 7, 2, 5, 3, 8, 14, 6, 11]
for i in range(0, len(list_1), 2) :
print(list_1[i])
Output
9
7
5
8
6
Python For Loop Increment by N
In the following example, we will use range() function to iterate over the elements of list using for loop in steps of n (read from user via console).
Example.py
step = int(input('Enter step value : '))
list_1 = [9, 5, 7, 2, 5, 3, 8, 14, 6, 11]
for i in range(0, len(list_1), step) :
print(list_1[i])
Output
Enter step value : 3
9
2
8
11
Conclusion
In this Python Tutorial, we learned how to use for loop with range() function, to loop through an iterable, and increment in steps.