Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Create a List of Random Numbers — The Most Pythonic Way

#1
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 n. Create a list of n elements in a certain interval (example interval: [0, 20]).

# n = 5 --> [2, 3, 1, 4, 3]
# n = 3 --> [10, 12, 1]
# n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]
https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" />

Solution: Here’s a quick overview on how you can create a list of random numbers:

  • Method 1: [random.random() for _ in range(10)] to create a list of random floats.
  • Method 2: [random.randint(0, 999) for _ in range(10)] to create a list of random ints.
  • Method 3: randlist = []; for _ in range(10): randlist.append(random.randint(0, 99)) to create a list of random ints.
  • Method 4: randlist = random.sample(range(20), 10) to create a list of random ints.

You can try those yourself in our interactive code shell:

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 [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.
# 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:

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 random.random() that generates a random float number between 0 and 1 each time it is called.

You call it ten times as defined in the context part for _ in range(10). Note that the underscore serves as a “throw-away” variable as you don’t actually need it to create the list.

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: [random.random() * 999 for _ in range(10)] would create a list of random floats in the interval [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]:

# 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:

print(randlist)
# [298, 218, 58, 260, 485, 192, 588, 615, 42, 499]

You use the random.randint(0, 999) function to create a random integer value between start value 0 and end value 999, so all created integers are in the interval [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):

# 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:

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 random.randint() function are independent.

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 random.sample() method takes a “universe” from which the random numbers are drawn and a list size n—and draws n random numbers from your universe.

# 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:

print(randlist)
# [1, 3, 0, 14, 7, 9, 13, 4, 12, 8]

You use the universe range(20) of the first 20 integer numbers 0, …, 19 and draw 10 random elements from the universe. Note that per default, no duplicates are allowed. If the universe is small than the list size n, an error is thrown:

ValueError: Sample larger than population or is negative

Discussion


In 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 random.sample() function as it’s implemented to do exactly this.

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 random.random() and random.randint() functions is already enough to solve the problem effectively. In practice, I don’t want to waste too much energy trying to remember code functions that do neither improve readability, nor efficiency of my code.

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!



https://www.sickgaming.net/blog/2020/07/...honic-way/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Create a Database Table with pyodbc in Python xSicKxBot 0 10 08-03-2020, 08:37 AM
Last Post: xSicKxBot
  [Tut] How to Create a List of Dictionaries in Python? xSicKxBot 0 29 07-09-2020, 11:37 AM
Last Post: xSicKxBot
  [Tut] Zip With List Output Instead of Tuple | Most Pythonic Way xSicKxBot 0 38 07-08-2020, 05:41 PM
Last Post: xSicKxBot
  [Tut] How to Create a Python List of Size n? xSicKxBot 0 39 07-06-2020, 12:09 PM
Last Post: xSicKxBot
  [Tut] How to Sort a List of Tuples? – Most Pythonic Way! xSicKxBot 0 41 07-04-2020, 01:38 PM
Last Post: xSicKxBot
  [Tut] Python List max() xSicKxBot 0 35 07-02-2020, 11:01 AM
Last Post: xSicKxBot
  [Tut] Dict to List — How to Convert a Dictionary to a List in Python xSicKxBot 0 36 06-30-2020, 04:53 AM
Last Post: xSicKxBot
  [Tut] The Most Pythonic Way to Remove Multiple Items From a List xSicKxBot 0 39 06-29-2020, 04:37 AM
Last Post: xSicKxBot
  [Tut] The Most Pythonic Way to Compare Two Lists in Python xSicKxBot 0 34 06-28-2020, 04:18 PM
Last Post: xSicKxBot
  [Tut] List Difference | The Most Pythonic Way xSicKxBot 0 34 06-27-2020, 02:51 PM
Last Post: xSicKxBot

Forum Jump:

[-]
Upcoming Events

[-]
Latest Threads
News - Nintendo Has Removed Pikmin 3 Fro...
Last Post: xSicKxBot
Yesterday 10:46 PM
» Replies: 0
» Views: 1
News - Fortnite Motorboat Mayhem Time Tr...
Last Post: xSicKxBot
Yesterday 10:46 PM
» Replies: 0
» Views: 1
Xbox Wire - Get Ready to Unleash Swimsan...
Last Post: xSicKxBot
Yesterday 08:05 PM
» Replies: 0
» Views: 4
News - What to expect when you’re expect...
Last Post: xSicKxBot
Yesterday 08:04 PM
» Replies: 0
» Views: 3
[Tut] Python One Line With Statement
Last Post: xSicKxBot
Yesterday 03:59 PM
» Replies: 0
» Views: 4
(Indie Deal) Bundles & Sales Round-up
Last Post: xSicKxBot
Yesterday 03:59 PM
» Replies: 0
» Views: 5
(Free Game Key) The Witcher: Enhanced Ed...
Last Post: xSicKxBot
Yesterday 03:59 PM
» Replies: 0
» Views: 4
News - Review: LEGO Super Mario – A Stro...
Last Post: xSicKxBot
Yesterday 03:58 PM
» Replies: 0
» Views: 4
News - NHL 20 Adds A New Way To Report T...
Last Post: xSicKxBot
Yesterday 03:58 PM
» Replies: 0
» Views: 3
News - Has The Chibi-Robo Studio Skip Pu...
Last Post: xSicKxBot
Yesterday 06:12 AM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2019