Python's Random Module: Generating Random Numbers

Explore Python's random module methods for generating, sampling, and manipulating random numbers and lists.

Discover how Python's random module can simplify generating random numbers, creating samples, and even mimicking real-world data like SAT scores or lottery tickets. Additionally, explore practical methods such as shuffling lists and picking random items with ease.

Key Insights

  • Learn how the random module generates random integers using methods like randint(), which allows specifying inclusive minimum and maximum values, and randrange(), useful for generating numbers within a specific range and interval steps.
  • Understand practical applications by generating realistic random data, such as SAT scores within the 400–800 range ending in zero, and random Olympic years ranging from 1896 to 2024 in increments of four.
  • Explore advanced randomization techniques including using random.sample() to produce unique random sets, random.shuffle() to randomize lists such as a deck of cards, and random.choice() to select a single random element from a list.

Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.

This is a lesson preview only. For the full lesson, purchase the course here.

The next module we're going to check out is random. The random module can generate random numbers. It can generate them in a range, and it can give you multiple random numbers that are unique—like a sample. It's really powerful.

Okay, so we're going to begin with just a raw random number. Say r for random is random.random()—the namesake method. So the random module has a random() method, just like the datetime module has a datetime property inside it. That will give you a 16-digit float from 0 to 1. There it is.

What's the usage of that? Well, I don't know—we could say r = random.random() and then multiply it by,000 and print that. Okay, that's not so useful. Yeah, but you could convert it to an int.

And now look what you've got. All of a sudden, you've got random integers in a range. So that is kind of useful.

Now in a program like JavaScript, you actually have to mechanically go through all the steps: first generate the float, then multiply it by your range max, and then round it off. We could just round this as well—you don't have to convert it to int. Why are they different? Because you're asking for a different random number twice.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

If you want to use the same random number, you could just say, don't do another random call—use the existing r. There—that's better, right? It's more clear. So there's a float with 16 decimal places and there's just the random int.

So that's one way to generate a random int. But there's a better way. You can just ask for a random int and specify a minimum and a maximum range.

The random module has a randint() method that takes two arguments: a min value and a max value (with the max being inclusive). It will return a random integer in that min-max range. So let's go ahead and get ourselves a random number.

Let's say r = random.randint(1,3). Such a narrow range is only used to demonstrate that the max value (3) is inclusive. If we never get a 3, that would suggest it's exclusive. There—you got your 3, which proves it's inclusive, right? If you ask for 1 to,000, you're going to sit here a while waiting for,000 to prove it's inclusive. So there you go—your random int from 1 to,000.

All right, so a little challenge. Let's read this and then turn off the recording. Give it a try, then come back to see how you did.

We're going to generate two random SAT scores. We did SAT scores before, but we weren’t generating random ones—we were letting the user input scores or we were hard-coding them.

Generate two random SAT scores: one Math, one English. Scores are in the 200–800 range. We'll make the minimum 400 so people don't get really low scores.

Your SAT score report will look something like this. Let's turn these off. We don’t want to give away the answers here, do we? No, we don’t.

Let’s get rid of that. So here, let’s say 560 and 710. It’s possible that your score could be something like that, right? Let’s go ahead and try.

We'll say—so turn off the recording. Try to get the random score and CONCATENATE it like so. CONCATENATE and print a score report.

Bonus: Make the scores end in a zero. SAT scores for individuals do end in zero. We could say something like, “Your SAT score is 570 and 710, ” right? To do that, maybe generate a random number between 40 and 80 and then multiply that by 10.

All right, turn off the recording, see what you can come up with, and then I will implement the solution. Okay—we’re back looking at the solution. We're going to say math_SAT = random.randint(400,800).

randint() takes a minimum (400) and a maximum (800), and it's inclusive. So there you go. Then we'll say the verbal or English score is the same deal.

Now to CONCATENATE that into a score report, you can start with the substrings. That's going to be a variable: math_SAT and eng_SAT. Remember, you cannot CONCATENATE numbers, so you'll have to stringify the SAT scores by wrapping them in str(). That should work.

Nope, what’s not working? Oh yeah—I’m missing a plus sign, and I’ve got another plus sign in the wrong place. Okay—there you go. Random! Wow—pretty good scores there, right?

Hello Harvard, yo.

Now to get them to end in zero, the little hack would be to not set the min and max to 400 to 800, but instead to 40 to 80—and then multiply the result by 10.

So you generate scores from 40 to 80 and multiply those by 10. That’s one way to do it. A little hacky, but it totally works. And there you go—these are ending in zeros, right? Because we're generating from 40 to 80, like 57, and multiplying by 10 gives you 570.

Okay, write that out, por favor. Yeah—you gotta do it. You gotta write it out, mate. All right—boom. You’re getting there.

All right, now you can also do this in a slicker way. This is a way to get your number ending in zero without multiplying by 10. You just provide a min, a max, and a step. If you step by 10, that means give me multiples of 10. If you step by 2, you'd only get even numbers. If you use step = 2 and start from 401, you'll get odd numbers.

Oh no—that's randint(). We can’t do that with randint(); we have to use randrange(). Wrong method. Okay—so randrange() takes min, max, and step.

To get the Math and English scores now, we would use randrange(400,801,10). Now everything ends in a zero. The concatenation is the same. Oh—that's randrange. There it is, ending in zeros.

Now to test this out—if you used a step of 2, all your values would be even. If you started from 401 and stepped by 2, all would be odd. But we want to start at 400, go to 800, and step by 10. Have the score end in a zero by adding a step of 10 as the third argument.

Challenge: Generate and print one Olympic year from the Summer Olympics. Okay—your min is 1896, and your max is 2024. That was the first modern Olympics: 1896,1900,1904, etc.

They skipped a couple of times—there were no Olympics in 1940 or 1944—but we don’t have to consider that. The 2020 Olympics actually occurred in 2021, but we also don’t have to worry about that.

So what we’ll do is generate a random Olympic year. We’ll say rand_olympic_year = random.randrange(1896,2025,4). Or I’d like you to do that. Generate a random Olympic year—you’re going to have to step correctly. Think about it. You’ll need to use start, stop, step—min, max, step. Turn off the recording, try to generate a random Olympic year, then come back and test your answer. Check your result.

Okay, so we're going to say olympic_year = random.randrange(1896,2025,4)—skipping and jumping by four. There you go: 2020,1976. That was the one in… where was that one in '76? I forget—Bruce Jenner—wasn't that Bruce Jenner? Anyway, moving along.

range(min, max) is exclusive—it returns all numbers in the min-max exclusive range. So you basically get a list. Let's say you want all the numbers from 1 to 10.

So here's what we're going to do. Let's say nums_list = range(1,11). We want numbers from 1 to 10. Since 10 is exclusive, we go to 11. When we print it, it doesn’t work because you have to listify it. We wrap it all in list() to unpack it. The numbers are there—they're just like in a suitcase. You can't see them. We unpack the list by listifying it. There you go.

Now here's another one—sample(). So that's how you listify a range—just like we did. list(range(min, max)). There's your max-exclusive behavior: 11 was excluded.

Now the next one we're going to look at is random.sample(), which is kind of neat. sample() gives you random numbers—as many as you like—and they're all unique, from a given range. If you wanted a random lottery ticket, you'd say: give me five numbers from, say, 1 to 69. You'd call that with a range and a count (how many you want), like 5, and pass that to random.sample().

So let’s try it out. We’ll say lottery_nums = random.sample(range(1,70), 5). These will be non-repeating numbers. Run it—and there it is.

Now, lottery tickets—if you look (you know, I’m not going to go into it), they report the winning numbers in ascending order. So let's say lottery_nums.sort(). If you recall, sort() is a list method we used in Lesson One. Now they're sorted in ascending order.

Now what about the Powerball number? Okay—let me show you Powerball. Powerball is five consecutive numbers from 1 to 69 (in ascending order), and then there’s a unique drawing from 1 to 26 called the Powerball. That number could be a repeat of one of the first five, because it's drawn independently.

If we wanted to get the sixth number—the Powerball—we’d just say: powerball = random.randint(1,26). Remember, randint() is inclusive. So that works. Print the Powerball—9, okay.

Now if you want to complete the ticket, you would append that last Powerball number to the list of lottery_nums. We say: lottery_nums.append(powerball). Then print the whole thing—you’ve got six numbers: five ascending from 1 to 69, and the Powerball. Run it enough times, and eventually… ah, there it is.

So notice that the Powerball number may repeat one of the five—because the Powerball is a separate drawing. It doesn’t know about the first five and isn't trying to avoid repeating them.

All right, another method we’re going to look at is shuffle(). It randomizes a list. Let’s say you have a list of consecutive integers and want to randomize them—say, a deck of cards.

So let’s make a list of consecutive integers from 1 to 52, representing a deck of cards, and then we’ll shuffle it. First, we’ll say: deck_of_cards = list(range(1,53))—listify that to unpack the suitcase of numbers. We could print that—there’s your 1 to 52. But it’s like a fresh deck of cards—you might want to shuffle it.

We’re going to say: random.shuffle(deck_of_cards). The shuffle() method is part of the random module and takes a list. It shuffles the list in place. You don’t need to assign it to a variable again. There—it shuffles it.

And if you want to deal yourself five cards, just grab the first five items: deck_of_cards[:5]. There’s five random cards—five random numbers from 1 to 52.

Now, picking a random number—there’s a method called choice() in random. It takes a list and returns a random item. We say: random_card = random.choice(deck_of_cards). Pick a card—any card. If you run it multiple times, it keeps picking new random values.

And that’s the last of the methods.

So just to recap: you’ve got random.choice(), random.shuffle(), random.sample(). You’ve got range(min, max), random.randrange(), random.randint(), and good old random.random(). We’ve taken a pretty good look at the datetime and random modules to get our feet wet with two important modules. This also introduces the concept of modules—along with the methods and properties they include, which are unique to each module.

All right—that is it for Lesson Three. Thank you so much—I hope you learned a lot. You're hanging with it. I know I'm talking a little fast—it’s a lot of material. I just need you to hit the pause button. That’s all. Hit the pause button, move back, camp out on a screen, freeze it. You don’t have to listen to me the whole time—just pause and type. Copy it, right?

You get to a point where you’re thinking, “This guy’s talking too fast”—okay, pause the guy. Mute me. Make me stop talking. Pause me and sit here and type this. Then move on to the next one and keep it rolling.

Really need you to type this. All righty—on to Lesson Four. We’ll see you when you're ready for that. Bye.

Brian McClain

Brian is an experienced instructor, curriculum developer, and professional web developer, who in recent years has served as Director for a coding bootcamp in New York. Brian joined Noble Desktop in 2022 and is a lead instructor for HTML & CSS, JavaScript, and Python for Data Science. He also developed Noble's cutting-edge Python for AI course. Prior to that, he taught Python Data Science and Machine Learning as an Adjunct Professor of Computer Science at Westchester County College.

More articles by Brian McClain

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram