chrisg
chrisg

Reputation: 41655

Even numbers in Python

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

Thanks

Upvotes: 24

Views: 92218

Answers (8)

pylang
pylang

Reputation: 44465

There are also a few ways to write a lazy, infinite iterators of even numbers.

We will use the itertools module and more_itertools1 to make iterators that emulate range().

import itertools as it

import more_itertools as mit


# Infinite iterators
a = it.count(0, 2)
b = mit.tabulate(lambda x: 2 * x, 0)
c = mit.iterate(lambda x: x + 2, 0)

All of the latter options can generate an infinite sequence of even numbers, 0, 2, 4, 6, ....

You can treat these like any generator by looping over them, or you can select n numbers from the sequence via itertools.islice or take from the itertools recipes e.g.:

mit.take(10, a)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

This is equivalent to list(range(0, 20, 2)). However, unlike range(), the iterator is paused and will yield the next batch of even numbers if run again:

mit.take(10, a)
# [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]

Details

The options presented are all infinite iterators that start with an integer, i.e. 0.

  • a. itertools.count yields the next value incremented by a step=2 (see equivalent code).
  • b. more_itertools.tabulate is an itertools recipe that maps a function to each value of a number line (see source code).
  • c. more_itertools.iterate yields the starting value (0). It then applies a function to the last item (incrementing by 2), yields that result and repeats this process (see source code).

1A third-party package that implements many useful tools, including itertools recipes such as take and tabulate.

Upvotes: 0

SLaks
SLaks

Reputation: 887285

Range has three parameters.

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

Upvotes: 70

Ray
Ray

Reputation: 1

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

b = [i for i in a if i % 2 == 0]

print("Original List -->", a,"\n")
print("and the Even Numbers-->", b)

Upvotes: 0

user3904440
user3904440

Reputation: 1

#This is not suggestible way to code in Python, but it gives a better understanding


numbers = range(1,10)

even = []

for i in numbers:

     if i%2 == 0:

       even.append(i)
print (even)

Upvotes: -1

Sapph
Sapph

Reputation: 6208

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.

Upvotes: 7

ghostdog74
ghostdog74

Reputation: 342313

>>> if 100 % 2 == 0 : print "even"
...
even

Upvotes: 0

ezod
ezod

Reputation: 7411

Try:

range( 0, 10, 2 )

Upvotes: 6

kgiannakakis
kgiannakakis

Reputation: 104168

Just use a step of 2:

range(start, end, step)

Upvotes: 12

Related Questions