Python Forum

Full Version: random.choice HELP
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi iam using random.choice and i want to ask you, how to know what element of array was choosen ?
example code

I need to store in variable what element from array was choosen. i mean number of element Is it possible ?

import random
array = ["Hello","Dog","Cat","Ball"]
x = random.choice(array)
print(x)
Here is one way

import random
array = ["Hello","Dog","Cat","Ball"]
x = random.choice(array)
print(f'Text -> {x} index -> {array.index(x)}')
Output:
Text -> Ball index -> 3
(Aug-08-2021, 10:58 AM)menator01 Wrote: [ -> ]Here is one way

import random
array = ["Hello","Dog","Cat","Ball"]
x = random.choice(array)
print(f'Text -> {x} index -> {array.index(x)}')
Output:
Text -> Ball index -> 3

THANK YOU A LOT
I
index = random.randint(0, len(array)-1)
x = array[index]
import random
array = ["Hello","Dog","Cat","Ball"]
x = random.choice(range(len(array)))
print(x, array[x])