Search code examples
pythonrandom

How to randomly select an integer from a list within a range?


I'm extracting some information from a CSV file into a list and would like a random value to be picked from that list. However, that value must exist within a specified range. For example, if I have a list like so:

[12, 100, 144, 50, 65, 30, 500, 450, 6]

and I have a range 55-300, I want to be able to randomly select any value from within this list that satisfies the range. Say, 100, 144 or 65 but never 12, 6, 30, etc.

I haven't been able to find the solution to this anywhere, and the random module doesn't seem to have any functionality that supports this directly. random.randrange() only produces a value from within a range, random.choice() only selects one element from a list, no range applies to it.

I'm essentially looking for a functionality that can possibly combine the two functions.


Solution

  • You can filter the numbers in your list to find the ones in the appropriate range, and pick one at random from those.

    lst = [12, 100, 144, 50, 65, 30, 500, 450, 6]
    number = random.choice([n for n in lst if 55 <= n <= 300])