Python tip 5: random choice and sample
Here are a couple of commonly used methods for the built-in
choice()method helps you get a random element
sample()method helps you get a
listof 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]
Both these methods will work on any sequence object. The
sample() method also accepts a
set object, but that will be deprecated.
See my 100 Page Python Intro ebook for a short, introductory guide for the Python programming language.