Alex Rivera | Logout

Why is a list needed for random.choice

Asked 2013-06-11T15:12:03.143
12

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?

Edit
Report

1 Answer

31

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

answered 2013-06-11T15:14:50.017

Your Answer