![]() |
|
[Tut] Create a List of Random Numbers — The Most Pythonic Way - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Create a List of Random Numbers — The Most Pythonic Way (/thread-96076.html) |
[Tut] Create a List of Random Numbers — The Most Pythonic Way - xSicKxBot - 07-07-2020 Create a List of Random Numbers — The Most Pythonic Way Do you want to initialize a list with some random numbers? In this article, I’ll show you four different way of accomplishing this—along with a short discussion about “the most Pythonic way”. Problem: Given an integer Code: nCode: nCode: # n = 5 --> [2, 3, 1, 4, 3]
# n = 3 --> [10, 12, 1]
# n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]![]() Solution: Here’s a quick overview on how you can create a list of random numbers:
You can try those yourself in our interactive code shell: https://trinket.io/embed/python/4a67c36fc2 Exercise: Change the interval of each method to [0, <your age>] and run the code. Method 1: List Comprehension to Random Float List [0, 1] List comprehension is a compact way of creating lists. The simple formula is Code: [expression + context]
Code: # Method 1: List Comprehension Random Float List [0, 1]
import random
randlist = [random.random() for _ in range(10)]In my Python shell, the result is the following: Code: print(randlist)
# [0.06472744987876633, 0.011889634172418173, 0.70189711954834, 0.030063483145627568, 0.22255082691969674, 0.26704646386061337, 0.3242939534531408, 0.1781476583083168, 0.5367990394305883, 0.7621210982784024]In the code, you first import the random module. Then, you create a list of random floats by repeatedly calling Code: random.random()You call it ten times as defined in the context part Code: for _ in range(10)Also note that the list comprehension statement evaluates the expression multiple times—and not only once in the beginning. That’s why all the numbers in the list are different. You can easily extend the creation of floats in a larger interval by multiplying the randomly created float with a constant: Code: [random.random() * 999 for _ in range(10)]Code: [0, 999]If you struggle with understanding list comprehension, watch my explainer video: Using list comprehension to generate a list of random numbers is readable, concise, and efficient. Were it not for the fourth method, I’d consider this to be the most Pythonic way to create a list of random floats. Method 2: List Comprehension to Random Integer List [0, 999] Just for the sake of completeness, here’s the list comprehension statement that creates a list of random integers in the interval [0, 999]: Code: # Method 2: List Comprehension Random Int List [0, 999]
import random
randlist = [random.randint(0, 999) for _ in range(10)]In my Python shell, the result is the following: Code: print(randlist)
# [298, 218, 58, 260, 485, 192, 588, 615, 42, 499]You use the Code: random.randint(0, 999)This is a very Pythonic and readable way to create a list of random integers. You can stop reading right away and use it in your own code. Method 3: For Loop Random Int List [0, 99] An alternative that’s often used by non-Python coders is to use a simple for loop that does the same thing as list comprehension (but demanding more space): Code: # Method 3: For Loop Random Int List [0, 99]
import random
randlist = []
for _ in range(10): randlist.append(random.randint(0, 99))In my Python shell, the result is the following: Code: print(randlist)
# [19, 35, 0, 13, 36, 15, 13, 65, 41, 99]Again, you use the throw-away underscore variable as the random number is not a function of a loop variable. Each two calls to the Code: random.randint()I’d consider this the least Pythonic way to solve this problem. Method 4: random.sample() Finally, we arrive at the most Pythonic way to solve this problem: stand on the shoulders of giants and use existing built-in functionality. The Code: random.sample()Code: nCode: nCode: # Method 4: random.sample()
import random
# Generate 10 random numbers between 0 and 20 (included)
randlist = random.sample(range(20), 10)In my Python shell, the result is the following: Code: print(randlist)
# [1, 3, 0, 14, 7, 9, 13, 4, 12, 8]You use the universe Code: range(20)Code: ValueError: Sample larger than population or is negativeIn this tutorial, you’ve learned four methods to solve the problem of creating a list of random numbers. Objectively, the most Pythonic way to accomplish this is the fourth method: use the Code: random.sample()But subjectively, I’d use the first or second method based on list comprehension to create a list of random floats or integers. Why? Because I’m lazy and knowing the Code: random.random()Code: random.randint()Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |