This is probably a very straight forward question but would love a simple explanation as to the why?
The below code requires a list in order to obtain a random card.
import random
card = random.choice (["hearts", "clubs", "frogs"])
I am puzzled as to why it requires a list and why I cannot do this.
import = random
card = random.choice("hearts" , "clubs", "frogs")
I'm fine that I can't do it I just would like to know why?
random() to select random value from a list. random. random() method generates the floating-point numbers in the range of 0 to 1. We can also get the index value of list using this function by multiplying the result and then typecasting it to integer so as to get the integer index and then the corresponding list value.
Python random.choice() function The choice() function of a random module returns a random element from the non-empty sequence. For example, we can use it to select a random password from a list of words. Here sequence can be a list, string, or tuple.
Because of Murphy's law: anything that can be done the wrong way will be done the wrong way by someone, some day. Your suggested API would require
random.choice(*lst)
when the values to choose from are in the list (or other sequence) lst
. When someone writes
random.choice(lst)
instead, they would always get lst
back instead of an exception. The Python principle that "explicit is better than implicit" then dictates that we have to type a few extra characters.
(Admitted, the result of random.choice("foobar")
pointed out by others may be surprising to a beginner, but once you get used to the language you'll appreciate the way that works.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With