Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Even numbers in Python

Tags:

python

range

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

Thanks

like image 629
chrisg Avatar asked Feb 02 '10 14:02

chrisg


4 Answers

Range has three parameters.

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

like image 58
SLaks Avatar answered Oct 22 '22 09:10

SLaks


Just use a step of 2:

range(start, end, step)
like image 37
kgiannakakis Avatar answered Oct 22 '22 11:10

kgiannakakis


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.

like image 40
Sapph Avatar answered Oct 22 '22 09:10

Sapph


Try:

range( 0, 10, 2 )
like image 25
ezod Avatar answered Oct 22 '22 11:10

ezod