A regular for
loop will increase its iteration counter by one in each iteration.
But there are situations where you want to increment the iteration counter by 2.
For some reason you might want to work with only even values.
Let’s see a few solutions for this.
range function
The solution to increment a for loop by 2 in Python is to use the range()
function.
This function allows you to specify three parameters: start
, stop
, and step
.
start
is the counter’s initial value, step
is by how much you want to increment until you reach the value of stop - 1
, because the value of stop is included.
The example bellow shows how to use range()
with a step of 2 starting from 0.
for i in range(0,20,2):
print(i)
The output:
0
2
4
6
8
10
12
14
16
18
Of course, you can use range()
to specify any step you would like, so if you want a step of 5, just do:
for i in range(0,20,5):
print(i)
The output is:
0
5
10
15
Slicing
If you never heard of slicing before, I recommend you to read Understanding Slicing in Python first, there is also a video linked in the article if you prefer.
Slicing is useful when you want to apply a different step when working with a pre-defined list.
In this case I have a list numbers
with the number from 1 to 16.
The logic is very similar to range()
, since you also have a start
, a stop
, and a step
.
In this case I’m starting on index 1, which is the number 2 in the list, remember lists are 0-indexed in Python.
I won’t put any stop
value since I want to go until the last index.
Finally, I put a step of 2.
numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in numbers[1::2]:
print(i)
The output will be:
2
4
6
8
10
12
14
16
Another way to implement the slicing from the code above is to combine range()
with len()
:
numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in range(1, len(numbers), 2):
print(numbers[i])
The output is the same:
2
4
6
8
10
12
14
16
Again, the same way we could use any step in range()
, we can change the step in slicing to anything we would like.
What about about float values?
An extra trick is how to achieve the same thing with float values.
In this case you have to use the library numpy and its function arange
.
This way you can use floats as start
, stop
, and step
.
import numpy as np
for i in np.arange(1.5, 2.5, 0.1):
print (i)
The output is:
1.5
1.6
1.7000000000000002
1.8000000000000003
1.9000000000000004
2.0000000000000004
2.1000000000000005
2.2000000000000006
2.3000000000000007
2.400000000000001