Home > Back-end >  How to detect which random did I chose from only one list with random.choice()?
How to detect which random did I chose from only one list with random.choice()?

Time:04-01

How can I detect which random number has been chosen from the list?


list = [3, 7, 5, 6, 3, 4, 1, 6]
random = random.choice(list)
print(random)

If random choice is 6, which 6 has been chosen from the list, how to know that?

CodePudding user response:

I don't think you can.

import random

list = [3, 7, 5, 6, 3, 4, 1, 6]

total = len(list)

target = random.randint(0, total)

print(list[target])
print("this is number "   str(target)   " on the list")

You can do this instead.

Output:

6 this is number 3 on the list


@Bamar noted that you actually want target = random.randrange(0, total) for the reasons explained.

CodePudding user response:

You can bypass the problem by indexing the original list and apply the random choice to it. In this particular case, with seeds' value equal to 26 and 27 to equal values are found but at different positions.

l = [3, 7, 5, 6, 3, 4, 1, 6]

import random

#random.seed(26)
random.seed(27)

index, random_value = random.choice(list(enumerate(l)))

print(f'index: {index}, value: {random_value}')

Output

index: 7, value: 6   # seed 27
index: 3, value: 6   # seed 26
  • Related