0

I want to generate a list of random integer within a range:

from random import randint lower = 0 upper = 20 length = 10 random_array = [randint(lower, upper) for _ in range(length)] 

I don't think it is elegant and I come up with another solution:

random_array = [randint(lower, upper)] * length 

But it generate a list of identical integers.

It might be that randint is executed before list.

I try putting off randint with lambda:

random_array = [(lambda: randint(lower, upper))()] * length 

but fail.

So I want to know if it's possible to delay the evaluation of items (randint in this case) and then have it triggered once the list is assembled?

7
  • 1
    How is this a duplicate? The OP does not require the numbers to be unique. Commented May 16, 2016 at 15:23
  • @Selcuk No, they don't. Commented May 16, 2016 at 15:24
  • The linked duplicate does not match the asker's specific issue. This may be more useful: stackoverflow.com/questions/240178/… Commented May 16, 2016 at 15:24
  • So you find [(lambda: randint(lower, upper))()] * length more elegant than [randint(lower, upper) for _ in range(length)] ? Commented May 16, 2016 at 15:25
  • 1
    I think the actual question is "how do I defer the actual generation of numbers without precomputing the whole list"? The real answer is the use of a generator function. Commented May 16, 2016 at 15:26

2 Answers 2

0
from random import randint lower = 0 upper = 20 length = 10 random_array = list() for _ in range(length): random_array.append(randint(lower, upper)) print random_array 
Sign up to request clarification or add additional context in comments.

Comments

-1
random_array = map(lambda _: randint(lower, upper), range(length)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.