To get a random element from an array in Python, you can use the random
module which provides various functions to work with random numbers.
One simple way to achieve this is by generating a random index using the randint
function from random
module and then accessing the element at that index in the array. Here's some sample code to illustrate this:
main.py200 chars12 lines
The randint
function generates a random integer between the two values provided as arguments (inclusive), and we pass the range of valid indices of the array as arguments. Finally, we use the obtained index to retrieve a random element from the array.
Note that there are several other ways to achieve the same thing in Python using different methods and functions provided by other libraries or even by the standard library itself.
gistlibby LogSnag