Pavan Kemparaju
Pavan Kemparaju

Reputation: 1611

Python Generating random even numbers using list comprehension

A contrived example to try and understand Python list comprehensions

I want to generate a list of 1000 random even numbers in the range of 1 to 100 This is what I have

import random
list = [random.randint(1,100) for _ in range(1,1000) if _ %2 ==0]

I am not able to figure out how to check the result of the randint() in the for loop.

I know this can possibly be done with random.randrange(x,y,2) or another mechanism. I want to understand if I can do it in the list comprehension way.

Upvotes: 0

Views: 8374

Answers (3)

Arezou Pakseresht
Arezou Pakseresht

Reputation: 1

import random
def my_generator():
    while True:
        yield random.randrange(0,10000,2)
a=my_generator()
print(next(a))

Every time you run this code,it generates an even number in range 0-10000(you can easily change start and stop in rangerandom.randrange(start,stop,step) here step=2 to generate even numbers)

Upvotes: 0

pstatix
pstatix

Reputation: 3848

Old post but:

from random import randint
even = sum(randint(1, 100) % 2 == 0 for _ in range(1, 1000))
print(even)

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54193

of course you can use a list comprehension, just not like this. What you could do instead is to write a function that produces a random even number, then do:

[your_func() for _ in range(1000)]

your_func in this case could be:

while True:
    n = random.randint(1, 100)
    if n%2 == 0:
        yield n

But of course this is hardly better than your noted possibility using random.randrange(2, 101, 2).

[random.randrange(2, 101, 2) for _ in range(1000)]

Upvotes: 5

Related Questions