get a random element from an array in python

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.py
import random

my_array = [1, 2, 3, 4, 5]

# generate random index
rand_index = random.randint(0, len(my_array) - 1)

# get random element
random_element = my_array[rand_index]

print(random_element)
200 chars
12 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