4

I have initiated a list of known length with zeros. I am trying to go back through the list and put random floating point numbers from 0-1 at each index. I am using a while loop to do this. However, the code is not putting the random numbers in. The list is still full of zeros and I do not understand why. I've inserted a print statement which is telling me the list is still full of zeros. I would appreciate any help!

randomList = [0]*10
index = 0
while index < 10:
    randomList[index] = random.random()
    print("%d" %randomList[index])
    index = index + 1
alko
  • 46,136
  • 12
  • 94
  • 102
JP1992
  • 49
  • 6

4 Answers4

7

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 it's elements as itegers with "%d" % randomList[index], so all those values are rounded to zero. You can use "%f" formatter to print float numbers:

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

or '{:M:Nf}.format':

>>> print("{.5f}".format(randomList[index]))
0.77639   
Community
  • 1
  • 1
alko
  • 46,136
  • 12
  • 94
  • 102
4

Why don't you print the list after the while?

...code...
print randomList

Output

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

If yout want your print statement work, use %f instead.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

A list comprehension is easier, faster:

randomList = [random.random() for _ in range(10)]
dansalmo
  • 11,506
  • 5
  • 58
  • 53
1
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)