tags:

views:

232

answers:

5

Hello,

Does anyone know if Python has an in-built function to work to print out even values. Like range() for example.

Thanks

+13  A: 

Range has three parameters.

You can write range(0, 10, 2).

SLaks
As does xrange()
Will
+1 for actual links to docs... why do so few people bother?
Peter Hansen
+4  A: 

Just use a step of 2:

range(start, end, step)
kgiannakakis
+3  A: 

Try:

range( 0, 10, 2 )
ezod
A: 
>>> if 100 % 2 == 0 : print "even"
...
even
ghostdog74
+2  A: 

I don't know if this is what you want to hear, but it's pretty trivial to filter out odd values with list comprehension.

evens = [x for x in range(100) if x%2 == 0]

or

evens = [x for x in range(100) if x&1 == 0]

You could also use the optional step size parameter for range to count up by 2.

Sapph
You could also write `map(lambda x: x * 2, range(0, 50))`
SLaks