1.4 Random Choice - nealtran1905/PythonForResearch GitHub Wiki
Often when we're using numbers, but also, occasionally, with other types of objects,
we would like to do some type of randomness.
For example, we might want to implement a simple random sampling process.
To this end, we can use the random module.
So the starting point is, again, to ### import that module, random. Let's think about a simple example where we have a set of numbers contained in a list, and we would like to pick one of those numbers uniformly at random. The function we need to use in this case is random.choice, and inside parentheses, we need a list. In this list, I'm going to just enter a few numbers-- 2, 44, 55, and 66. And then when I run the random choice, Python returns one of these numbers back to me. If I repeat the same line, I'm going to get a different answer, because, again, Python is just picking one of those objects at random. A crucial thing to understand about the random choice method
is that Python doesn't care about the fundamental nature of the objects that
are contained in that list.
What that means, instead of using numbers, I could also be choosing one out of several strings. So let's see how that might work. I'm going to go back to my list. I'm just going to include three short strings here. Let's just do "aa," "bb," and "cc." I can ask Python to pick one of these uniformly at random. So Python doesn't care about the nature of these objects.