# Random Float Numbers in Python

Hello, a complete Python beginner here (like minutes ago)
I would like to learn how to create a random list of 20 float values that are a mix of these float values 0.5, 0.75, 1.0, 1.5, 1.75, 2.0 but I don’t want any of the resulting float values next to each other the same.

Can anyone help?

random numbers

random stepped numbers

shuffling list

if you are just starting out, it would be best to read through these examples and work with them to get your result.

thank you rgr, will do.

@FordEarl welcome to python. somemething like this might work:

#import random module
import random

#initialize list with values
val = [0.5, 0.75, 1.0, 1.5, 1.75, 2.0]

#create random index and insert first item in new list
randomindex = random.randint(0, len(val)-1)
randList = [val[randomindex]]

#iterate desired amount of times
for i in range(20):
#change the index value until its not the same as the previous
while randList[-1] == val[randomindex]:
randomindex = random.randint(0, len(val)-1)
#append value to new list
randList.append(val[randomindex])

print randList

There probably won’t be a python built-in way to not choose the same value twice (I think that is what you are asking), as that probably isn’t really ‘random’, but it is a useful constraint. Here is another possible solution:

import scriptcontext as sc
import rhinoscriptsyntax as rs
import Rhino as R
import random

choices = [0.5, 0.75, 1.0, 1.5, 1.75, 2.0]
chosen = []

n = 20

# protect from infinite loops
# make sure there is more than 1 choice in choices list
if len(set(choices)) > 1:
# keep track of last choice
last_choice = None
for i in range(n-1):
# pick a number randomly
candidate = random.choice(choices)
# if the candidate is the same as the last choice, try again until it isn't
# this will go on forever if conditions allow, you may want to limit total attempts
while candidate == last_choice:
# print just for fun
print('duplicate choice on try {}'.format(i))
candidate = random.choice(choices)
# candidate should now not be the same as last choice
chosen.append(candidate)
# update the last choice
last_choice = candidate

print(chosen)

sample output:

duplicate choice on try 2
duplicate choice on try 4
duplicate choice on try 12
[1.0, 2.0, 0.5, 0.75, 1.5, 0.75, 2.0, 1.0, 1.75, 1.0, 0.5, 2.0, 1.0, 1.5, 1.0, 0.5, 0.75, 2.0, 0.75]