So imagine I want to go over a loop from 0 to 100, but skipping the odd numbers (so going "two by two").
for x in range(0,100):
if x%2 == 0:
print x
This fixes it. But imagine I want to do so jumping two numbers? And what about three? Isn't there a way?
(Applicable to Python <= 2.7.x only)
In some cases, if you don't want to allocate the memory to a list then you can simply use the xrange() function instead of the range() function. It will also produce the same results, but its implementation is a bit faster.
Python 3 actually made
range
behave likexrange
, which doesn't exist anymore.If you are using an IDE, it tells you syntax:
min, max, step(optional)
Use the step argument (the last, optional):
Note that if you actually want to keep the odd numbers, it becomes:
Range is a very powerful feature.