Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count by twos with Python's 'range'

Tags:

python

range

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?


1 Answers

Use the step argument (the last, optional):

for x in range(0, 100, 2):
    print(x)

Note that if you actually want to keep the odd numbers, it becomes:

for x in range(1, 100, 2):
    print(x)

Range is a very powerful feature.

like image 71
Jivan Avatar answered Sep 12 '25 05:09

Jivan