What is the difference between Random.Choice and Random.Choices in Python?

Asked

Viewed 303 times

3

I know they both draw random numbers, but what’s the difference between them ?

  • If the answer below solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

1 answer

6

There are two fundamental differences:

  1. random.choice returns an element of the drawn sequence, while random.choices returns a list of elements of the drawn sequence
  2. random.choices accepts weights for the observations, while the weight of the observations is equal for all elements in random.choice

See how the difference in the arguments of the function allows to infer these differences:

Arguments random.choice

import random
import inspect

#argumentos random.choice
inspect.getfullargspec(random.choice)
FullArgSpec(args=['self', 'seq'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})

Arguments random.choices

#argumentos random.choices
inspect.getfullargspec(random.choices)
FullArgSpec(args=['self', 'population', 'weights'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=['cum_weights', 'k'], kwonlydefaults={'cum_weights': None, 'k': 1}, annotations={})

An example of random selection of a sequence using random.choices:

import random

#seleciona dois números a partir de um vetor de observações e um vetor de pesos
print(random.choices([1,4,2,7,4,2,8,9], [0.2,0.4,0.6,0.3, 0.5,0.4,0.7,0.3], k=2)) #[4,8] no meu caso

Note that this example cannot be replicated using random.choices, because there is no option to apply weights. But if the user wanted to create a list, it would also be possible, using comprehensilist on:

[random.choice([1,4,2,7,4,2,8,9]) for k in range(2)]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.