Search code examples
pythonrandomarguments

random.choice() takes two arguments?


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

import random

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

print(rollDie())

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

Traceback (most recent call last):
  File "Lecture 5.2 -- stochastic - die roll example.py", line 8, in <module>
    print(rollDie())
  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 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)?


Solution

  • 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."""
        try:
            i = self._randbelow(len(seq))
        except ValueError:
            raise IndexError('Cannot choose from an empty sequence') from None
        return seq[i]