Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a list needed for random.choice

Tags:

python

list

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?

like image 371
Danrex Avatar asked Jun 11 '13 15:06

Danrex


People also ask

How do you use a random list?

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.

Why do we use the random choice () method in Python?

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.


1 Answers

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.)

like image 169
Fred Foo Avatar answered Oct 15 '22 00:10

Fred Foo