Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
random.choice HELP
#1
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)
Reply
#2
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
samuelbachorik likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#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
Reply
#4
I
index = random.randint(0, len(array)-1)
x = array[index]
Reply
#5
import random
array = ["Hello","Dog","Cat","Ball"]
x = random.choice(range(len(array)))
print(x, array[x])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  combobox_callback(choice choice part of openfile name (kind of dependency) janeik 9 1,431 Sep-10-2023, 10:27 PM
Last Post: janeik
  Unable to use random.choice(list) in async method spacedog 4 3,412 Apr-29-2021, 04:08 PM
Last Post: spacedog
  Help with a random.randint choice in Python booponion 5 2,766 Oct-23-2020, 05:13 PM
Last Post: deanhystad
  ???: if "{choice}" in self._command BaiYouLing4 3 2,004 Aug-23-2020, 05:40 AM
Last Post: BaiYouLing4
  trying to input a variable using random.choice python63 9 3,586 Aug-13-2020, 05:37 PM
Last Post: python63
  Random Choice Operations Souls99 6 2,903 Jul-31-2020, 10:37 PM
Last Post: Souls99
  random.choice() takes two positional arguments, but three were given. ShakeyPakey 5 11,628 May-31-2020, 03:13 PM
Last Post: deanhystad
  random.choice Sensing Nonexistent Argument Millionsunz 3 5,803 Nov-28-2016, 05:57 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020