Sara Ch
Sara Ch

Reputation: 3

Generating a random with a specific limited size

Could someone explain to me how I can use random to generate a list consisting of numbers that differ from 0 to 9 and the size should be fixed between 49 and 98?

random_number = [random.randint(0,9) for _ in range()]

I think I should use this line, but I am not sure how to limit the random_number which gets generated to be a number consisting of 49 to 98 numbers.

Could someone help me clarifying this?

Upvotes: 0

Views: 58

Answers (2)

BRIAN BURGESS
BRIAN BURGESS

Reputation: 21

[random.randint(0,9) for _ in range(random.randint(49,98))]

This should do what you want, no? Range accepts a number, so if we randomly generate a number between 49 and 98 and pass it to range, we'll get a list of 49 to 98 items, which will be iterated over.

Edit: Seems a comment beat me to it. Tragic.

Upvotes: 0

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can use random.choices to generate a list of random entries from a range, pass k= to determine the size. We can pass k=random.randint(49, 98) to generate a list with a random length in that range

import random
random.choices(range(0, 9), k=random.randint(49, 98))

Upvotes: 2

Related Questions