25

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?

3 Answers3

68

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.

cinemassacres
  • 389
  • 4
  • 16
Jivan
  • 21,522
  • 15
  • 80
  • 131
  • You've just edited it, but I guess `step=2` also worked. Am I wrong? –  Dec 28 '14 at 16:12
  • @JuanRocamonde range() doesn't take keyword arguments, in fact – Jivan Dec 28 '14 at 16:13
  • Ok so that means it wouldn't. Thanks for your reply –  Dec 28 '14 at 16:13
  • @JuanRocamonde Is that what you were asking for? – Jivan Dec 28 '14 at 16:15
  • @JuanRocamonde don't forget to accept the answer so that other users can identify it (only if you're actually happy with that) – Jivan Dec 28 '14 at 16:21
  • Yes once the timer lets me :) –  Dec 28 '14 at 16:22
  • 2
    I think your answer might have a mistake, since `range(1, 100, 2)` starts iterating with `1` and thus skips the _even_ numbers, whereas `range(0, 100, 2)` starts iterating at `0` and thus skips the _odd_ numbers. – David Z Dec 28 '14 at 21:09
  • @DavidZ right! non-English speaker, I always confuse odd/even :) answer edited, thanks – Jivan Dec 28 '14 at 21:10
3

(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.

for x in xrange(0,100,2):
    print x,   #For printing in a line

>>> 0, 2, 4, ...., 98 

Python 3 actually made range behave like xrange, which doesn't exist anymore.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ZdaR
  • 22,343
  • 7
  • 66
  • 87
3
for i in range(0, 100, 2):
    print i

If you are using an IDE, it tells you syntax:

min, max, step(optional)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131