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?
Here I use the sample
method to generate 10 random numbers between 0 and 100.
Note: I'm using Python 3's range
function (not xrange
).
import random
print(random.sample(range(0, 100), 10))
The output is placed into a list:
[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]
import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]
xrange()
will not work for 3.x.
numpy.random.randint().tolist()
is a great alternative for integers in a specified interval:
#[In]:
import numpy as np
np.random.seed(123) #option for reproducibility
np.random.randint(low=0, high=100, size=10).tolist()
#[Out:]
[66, 92, 98, 17, 83, 57, 86, 97, 96, 47]
You also have np.random.uniform()
for floats:
#[In]:
np.random.uniform(low=0, high=100, size=10).tolist()
#[Out]:
[69.64691855978616,
28.613933495037948,
22.68514535642031,
55.13147690828912,
71.94689697855631,
42.3106460124461,
98.07641983846155,
68.48297385848633,
48.09319014843609,
39.211751819415056]
This is way late but in-case someone finds this helpful.
You could use list comprehension.
rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)
Output:
[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]
Cheers!
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)
Fix the indentation of the print
statement
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1,101,1))
print (my_randoms)
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
my_randoms = [randint(n1,n2) for x in range(listsize)]
Source: Stackoverflow.com