
1. Overview
In this article, we will learn to increment for loop by 2 in Python.
2. Python for loop increment by 2
Sometimes, you want to loop through a for loop in increments of 2.
You can use a range
with a step size of 2.
The xrange()
function in Python is used to generate a sequence of numbers, similar to the range()
function. However, we can use xrange()
only in Python 2.x whereas range()
in Python 3.x.
2.1. Python 2:
The general syntax for defining the xrange
is:
xrange(start,end,step)
This defines a range of numbers from start (inclusive) to end (exclusive). The range function can take three parameters:
- Start: Specify the starting position of the sequence of numbers (optional).
- End: Specify the ending position of the sequence of numbers (mandatory).
- Step: The difference between each number in the sequence (optional).
By default, the start and step values are 0 and 1.
for i in xrange(0,10,2): print(i) 2 4 6 8
2.2. Python 3
The range
type represents an immutable sequence of numbers and you can use it to loop a specific number of times in for
loops.
The arguments to the range constructor must be integers. The default value of the step argument is 1
and the start
is 0. If the step is zero, Python throws ValueError
.
For a positive step, the contents of a range r
are determined by the formula r[i] = start + step*i
where i >= 0
and r[i] < stop
.
For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i
, but the constraints are i >= 0
and r[i] > stop
.
class range(stop) class range(start, stop[, step])
start: The value of the start parameter (or 0
default value)
stop: The value of the stop parameter
step: The value of the step parameter (or 1
default value)
for i in range(0,10,2): print(i) 2 4 6 8
Note: Use xrange
in Python 2 instead of range
because it is more efficient as it generates an iterable object, and not the whole list.
3. Conclusion
To sum up, we have learned to increment for loop by 2 in Python.