Random.choice() takes 2 positional arguments but 3 were given

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Random.choice() takes 2 positional arguments but 3 were given #

The Python "TypeError: Random.choice() takes 2 positional arguments but 3 were given" occurs when we pass multiple, comma-separated arguments to the random.choice() method. To solve the error, pass a list to the method, e.g. random.choice(['a', 'b']).

random choice takes 2 positional arguments but 3 were given

Here is an example of how the error occurs.

main.py
import random # ⛔️ TypeError: Random.choice() takes 2 positional arguments but 3 were given print(random.choice('a', 'b'))

We passed multiple, comma-separated arguments to the random.choice() method, but the method takes a single argument - a sequence.

To solve the error, group the arguments into a list.

main.py
import random print(random.choice(['a', 'b'])) # 👉️ "a"

The list can contain as many items as necessary.

The random.choice method takes a sequence and returns a random element from the non-empty sequence.

If the sequence is empty, the method raises an IndexError.

If you need to get multiple random values from a sequence, use the random.choices method instead.

main.py
import random print(random.choice(['a', 'b', 'c'])) # 👉️ b print(random.choices(['a', 'b', 'c'], k=2)) # 👉️ ['b', 'a']

The random.choices method takes a sequence and a k keyword argument and returns a k sized list of elements chosen from the sequence.

If the sequence is empty, the method raises an IndexError.

Conclusion #

The Python "TypeError: Random.choice() takes 2 positional arguments but 3 were given" occurs when we pass multiple, comma-separated arguments to the random.choice() method. To solve the error, pass a list to the method, e.g. random.choice(['a', 'b']).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.