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?

Rahn
  • 4,787
  • 4
  • 31
  • 57
  • 1
    How is this a duplicate? The OP does not require the numbers to be unique. – Selcuk May 16 '16 at 15:23
  • @Selcuk No, they don't. – Rahn May 16 '16 at 15:24
  • The linked duplicate does not match the asker's specific issue. This may be more useful: http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly –  May 16 '16 at 15:24
  • So you find `[(lambda: randint(lower, upper))()] * length` more elegant than `[randint(lower, upper) for _ in range(length)]` ? – polku May 16 '16 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. – Selcuk May 16 '16 at 15:26
  • @Selcuk Thanks! Very close! But actually I want to know about the order of item evaluation and list assemble. – Rahn May 16 '16 at 15:29
  • Sorry, I misinterpreted the complaint about one of the proposed methods generating a list of identical numbers to mean that it was intended to be a sample of the range. You could sub a list comp with `random.choice` and it would still be better than any of the proposed solutions in the question, and other answers on the linked dupe would also work with easy mods. (e.g. add to list instead of add to set) – Two-Bit Alchemist May 16 '16 at 15:41

2 Answers2

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
Bryce Drew
  • 5,777
  • 1
  • 15
  • 27
-1
random_array = map(lambda _: randint(lower, upper), range(length))
Paul Becotte
  • 9,767
  • 3
  • 34
  • 42