Create a 'list' called my_randoms of 10 random numbers between 0 and 100.
This is what I have so far:
import random my_randoms=[] for i in range (10): my_randoms.append(random.randrange(1, 101, 1)) print (my_randoms)
Unfortunately Python's output is this:
[34] [34, 30] [34, 30, 75] [34, 30, 75, 27] [34, 30, 75, 27, 8] [34, 30, 75, 27, 8, 58] [34, 30, 75, 27, 8, 58, 10] [34, 30, 75, 27, 8, 58, 10, 1] [34, 30, 75, 27, 8, 58, 10, 1, 59] [34, 30, 75, 27, 8, 58, 10, 1, 59, 25]
It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?
The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50. To generate random integers between 0 and 9, you can use the function randrange(min,max) .
An array of random integers can be generated using the randint() NumPy function. This function takes three arguments, the lower end of the range, the upper end of the range, and the number of integer values to generate or the size of the array.
Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.
import random my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]
You could use random.sample
to generate the list with one call:
import random my_randoms = random.sample(range(100), 10)
That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):
my_randoms = random.sample(range(1, 101), 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With