apotheosied apotheosied - 4 months ago 25
Python Question

Python 3.5 random.choice()

I made a simple mistake in the following roll die roll function:

import random

def rollDie():
return random.choice(1,2,3,4,5,6)


I do know that I need to pass the sequence as a list, but I was more curious about the error message. I received following the error:

Traceback (most recent call last):
File "Lecture 5.2 -- stochastic - die roll example.py", line 8, in <module>
File "Lecture 5.2 -- stochastic - die roll example.py", line 6, in rollDie
return random.choice(1,2,3,4,5,6)
TypeError: choice() takes 2 positional arguments but 7 were given

The error message says "choice() takes 2 positional arguments but 7 were given".

But the documentation indicates only one argument (sequence). https://docs.python.org/3/library/random.html

What is the second argument (or seventh in my case)? Is this the seed (which I have not specified so is being initialised by the clock)?

Answer Source

choice() is a method on the hidden Random() instance the random module maintains. Because it is a method, it has 2 arguments: self and the iterable from which to make a choice.

From the module documentation:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class.

and the random module source code:

def choice(self, seq):
    """Choose a random element from a non-empty sequence."""
        i = self._randbelow(len(seq))
    except ValueError:
        raise IndexError('Cannot choose from an empty sequence') from None
    return seq[i]