three random numbers from a given in python

To get three random numbers from a given list of numbers, we can use the random.sample() method. This method requires two arguments - the list of numbers and the number of random numbers to be selected.

main.py
import random

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

random_numbers = random.sample(numbers, 3)

print(random_numbers)
120 chars
8 lines

In the above code, we import the random module and create a list of numbers. We then use the random.sample() method to select three random numbers from the list, which is stored in the random_numbers variable. Finally, we print the random_numbers variable to display the selected random numbers.

Note that using random.sample() will raise a ValueError if the number of random elements requested is larger than the length of the given list.

gistlibby LogSnag