Creating a list of random numbers in python

I started a list of known lengths with zeros. I am trying to go back through a list and put random floating point numbers from 0-1 for each index. For this, I use a while loop. However, the code does not put random numbers. The list is still full of zeros, and I don't understand why. I inserted a print statement that tells me that the list is still full of zeros. I would be grateful for any help!

randomList = [0]*10
index = 0
while index < 10:
    randomList[index] = random.random()
    print("%d" %randomList[index])
    index = index + 1
+4
source share
4 answers

The list is random:

>>> randomList
[0.46044625854330556, 0.7259964854084655, 0.23337439854506958, 0.4510862027107614, 0.5306153865653811, 0.8419679084235715, 0.8742117729328253, 0.7634456118593921, 0.5953545552492302, 0.7763910850561638]

But you print its elements as itegers with "%d" % randomList[index], so all of these values ​​are rounded to zero. You can use the format "% f" to print floating point numbers:

>>> print("%.5f" % randomList[index])
0.77639

'{: M: Nf}.format':

>>> print("{.5f}".format(randomList[index]))
0.77639   
+7

while?

...code...
print randomList

[0.5785868632203361, 0.03329788023131364, 0.06280615346379081, 0.7074893002663134, 0.6546820474717583, 0.7524730378259739, 0.5036483948931614, 0.7896910268593569, 0.314145366294197, 0.1982694921993332]

, print , %f .

+4

Understanding the list is easier and faster:

randomList = [random.random() for _ in range(10)]
+2
source
import random
from pprint import pprint

l = []

for i in range(1,11):
    l.append( int(random.random() * (i * random.randint(1,1e12))) )

pprint(l)
+1
source

All Articles