Problem with random

I have a list which currently has 2 objects. I do this calculation to get one of them randomly:

import random

list = ["1", "2"]
r = random.randint(0, len(list) - 1)

This had to output value between 0 and 1, but it outputs value between 0, 1 and 2. Why?

Found it - I had one other object in list(i use this:

for obj in scene.objects:
if "prop" in obj:

And I had accidently added that prop to another object:D

A new problem occured:
Now I have 3 objects in the list and I need the script to not to set the number to the current one. That means: if r = 0 and it chooses 0 again, it should start choosing again even if the sensor is inactive. I don’t know how to!

See if you can solve this one. I think it’s a similar problem. This thing is doing auto-align on all objects in the scene but it never stops. LOL


autoAlign.blend (120 KB)

random.shuffle(mylist) should do what you want

Shuffle? What does it do?

not sure if i understood but maybe
while r == 0
can help

OK! I figured it out a bit differently. Using a property instead of variable somehow fixed it.

You can also use random.choice to pick a random entry from a list. No need to figure out the length of your list and generate integers.

myList = [0,1,2,3,4,5,"mustache", False, 62]
r = random.choice(myList)

If you want to re-choose when it finds the choice you already have, you can use recursion:

myChoice = myList[0]
r = random.choice(myList)
while r == myChoice:
    r = random.choice(myList)

Thanks Nines! This helps! :slight_smile:

Be careful with the while loops though, it’s totally possible for it to get in a situation where it gets stuck in an endless loop and lock up the game. This is why I had myChoice equal an item on the list, rather than something like myChoice = 0

I kind of got the logic backwards there, but hopefully you get what I’m trying to say (it’s been one of those days…)

I did a short tutorial on the random module that you might find useful.