Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a random.random() result into a list - Python

I'm trying to create a list that pulls ten random real numbers between 30 and 35 and prints them out on a list. When I run the below code I get the following error:

TypeError: 'float' object is not iterable.

Here's the code:

lis = list(range(10))
random.seed(70)
for i in range(0, len(lis)):
    randreal = (random.random()*5 + 30)
    lis = list(randreal)
    print(lis)

I feel like I'm missing something obvious. When I run the code without

lis=list(randreal)
print(lis)

I get the results I want, just not in a list. Also I'm trying to do this without random.uniform

like image 538
Rob Avatar asked Aug 26 '17 22:08

Rob


Video Answer


2 Answers

You write:

lis = list(randreal)

But list(..) is here a constructor. The constructor looks for an iterable object (another list, a set, a dictionary, a generator, etc.) that it can turn into a list. A floating point is not iterable, so it can not construct a list for that. It will thus error.

One way to solve it is to assign to an index of the list lis:

lis = [0] * 10
random.seed(70)
for i in range(0, len(lis)):
    randreal = (random.random()*5 + 30)
    lis[i] = randreal  # assign to an index
    print(lis)

But this is still not very elegant: you first construct a list, and then later modify it. You can improve the code by drawing 10 elements and each time .append(..) to the list:

lis = []
random.seed(70)
for i in range(0,10):
    randreal = (random.random()*5 + 30)
    lis.append(randreal)  # append to the list
    print(lis)

This is already better, but still it is a lot of code, so we can use list comprehension to make it more declarative:

random.seed(70)
lis = [random.random()*5 + 30 for _ in range(10)]
print(lis)
like image 182
Willem Van Onsem Avatar answered Oct 01 '22 12:10

Willem Van Onsem


You first created list lst [0,1,2,3,4,5,6,7,8,9]. This is unnecessary. Then you are trying to overwrite this list lst with new list list(randreal) which throws error, because its not valid list constructor

You can either start with empty list and append every random number you created:

lis = []
random.seed(70)
for i in range(10):
    randreal = (random.random()*5 + 30)
    lis.append(randreal)
print(lis)

or overwrite each value of original list with new random value

lis = list(range(10))
random.seed(70)
for i in range(0, len(lis)):
    randreal = (random.random()*5 + 30)
    lis[i] = randreal
print(lis)
like image 42
Tomáš Zahradníček Avatar answered Oct 01 '22 12:10

Tomáš Zahradníček