summer pan
summer pan

Reputation: 35

random list within a certain limit

i want to generate a random list, in which generates n numbers between a and b. However, when executing, nothing comes out.

def random_list(a,b,n):
    import random
    xs=[]
    x=random.randint(a,b)
    xs.append(x)
    while len(xs)==n:
        return xs

Upvotes: 1

Views: 69

Answers (2)

nbohra
nbohra

Reputation: 21

A small change in logic and small code move should fix it.

def random_list(a,b,n):
    import random
    xs=[]
    while len(xs)!=n:
        x=random.randint(a,b)
        xs.append(x)
        return xs

Also as others have mentioned, if you aware of list comprehension then please use them. That will make code much cleaner.

Upvotes: 1

Tibebes. M
Tibebes. M

Reputation: 7548

try this one (using randint with list comprehension to generate the random list)

import random

def random_list(a,b,n):
    xs = [random.randint(a,b) for _ in range(n)]
    return xs

output:

>>> print(random_list(1, 10, 4))
[6, 2, 6, 4]

>>> print(random_list(1, 10, 4))
[3, 9, 2, 1]

If you wish to keep the while loop, you could re-arrange your code to something like this:

import random

def random_list(a,b,n):
    xs=[]
    while len(xs) < n:
        x = random.randint(a,b)
        xs.append(x)
    return xs

Upvotes: 1

Related Questions