Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Sometimes we want a random item out of a collection full of items. Luckily, Python gives us a method that does exactly that.
There's lots more to explore in the random
library. Be sure to check it out with dir()
and help()
.

0:00
In the final stage of Python Basics, we talked about using the random library and

0:04
its rand int method to get a random integer.

0:07
Now, let's look at the choice method from the random library and

0:10
how to use it with iterables.

0:12
So, just like using random back in Python Basics, we need stuff for

0:17
random to work with.

0:18
So, let's get a list and we'll have a lot of items in that list.

0:26
My list is the numbers zero through 49.

0:30
And then to use random, I have to import it.

0:33
So, I will import random.

0:35
And so choice, let's look at choice, random.choice.

0:42
So we pass in a sequence, in our case, an iterable, we're gonna pass in our list.

0:48
And it will choose a random element out of that.

0:51
So, it's just as easy to use as rand int was.

0:56
Let's let's try using this though.

0:58
Let's do random.choice from my_list, and we get back 15.

1:05
Now, if we run that again, we'll get a different number.

1:08
So we keep getting these different numbers.

1:11
And this is gonna work no matter what's in our list.

1:13
So, let's just do random.choice and

1:16
let's make a new list, and we'll say, we're gonna add a bunch of tuples.

1:24
And 4, 5.

1:26
All right, so we have a list of tuples.

1:29
And we get back our 0 and our 1.

1:31
So, you can only use random.choice on iterables that have indexes.

1:35
You can't use it on a dictionary to get a random key.

1:39
You don't have to do that for this challenge or

1:41
you shouldn't have to, but it's good to know that restriction exists.

1:44
If we were to try doing that and do say,

1:49
a is True and b is False, we get back a KeyError.

1:56
Great.

1:56
Hopefully, you get some good selections from that.

1:59
In our next video, we'll do some planning for

2:01
our game, but feel free to start writing it yourself now.
You need to sign up for Treehouse in order to download course files.
Sign up