Reputation: 5646
In Python 3.x, I need to choose an integer at random among the indices of a given list. In other words, given
mylist = [0, 5, 6, 8, -10]
I want to return a number between 0 and 4. What's the most Pythonic way to do it? I tried
import numpy as np
my_list = [0, 5, 6, 8, -10]
def choose_at_random(a_list):
choice = np.random.randint(0, len(a_list))
return choice
This works, but is this the Pythonic way to do it?
Upvotes: 0
Views: 66
Reputation: 16184
If you just want to use something from Python's standard library (and don't need anything vectorised like numpy
) randrange
is generally the easiest method for accomplishing this.
You'd use it something like:
from random import randrange
from typing import Sized
def random_index_from_sized(a_list: Sized) -> int:
return randrange(len(a_list))
my_list = [0, 5, 6, 8, -10]
random_index_from_sized(my_list)
which would return an integer value in [0, 4].
numpy
's randint
is similarly defined, so could be used in the above definition as:
from numpy.random import randint
def random_sized_index(a_list: Sized) -> int:
return randint(len(a_list))
Returning a single value from numpy
is kind of pointless, i.e. numpy
is designed for returning large arrays. A quick timeit
test says that randrange(5)
takes ~0.3µs while randint(5)
takes ~2µs (for a single value). If you want, e.g., 1000 values then [randrange(5) for _ in range(1000)]
takes ~300µs, while randint(5, size=1000)
only takes ~20µs.
Upvotes: 1
Reputation: 9
import random
#random is in the standard library(so no need to "pip")
my_list = [0, 5, 6, 8, -10]
def choose_at_random(a_list):
choice = (random.choice(a_list))
return choice
Upvotes: 0