Here are a couple of commonly used methods for the built-in random module:

  • choice() method helps you get a random element
  • sample() method helps you get a list of a specific count of random elements
>>> import random
>>> nums = [1, 4, 5, 2, 51, 3, 6, 22]

>>> random.choice(nums)
3

>>> random.sample(nums, k=4)
[51, 2, 3, 1]

>>> random.sample(range(1000), k=5)
[490, 26, 9, 745, 919]

info Both these methods will work on any sequence object. The sample() method also accepts a set object, but that will be deprecated.

Video demo:


info See my 100 Page Python Intro ebook for a short, introductory guide for the Python programming language.