Get random number from set deprecation

Viewed 2007

I am trying to get a random n number of users from a set of unique users.

Here is what I have so far

users = set()

random_users = random.sample((users), num_of_user)

This works well but it is giving me a deprecated warning. What should I be using instead? random.choice doesn't work with sets

UPDATE

I am trying to get reactions on a post and want them to be unique which is why I used a set. Would it be better to stick with a list for this?

users = set()
    for reaction in msg.reactions:
        async for user in reaction.users():
            users.add(user)
2 Answers

Convert your set to a list using * operator to unpack your dict:

random_users = random.choices([*users],k=num_of_user)

You can also create a list, and make the elements unique later. For this, a common way is to convert your list to a set, and back to a list again.

FWIW, random.sample() in Python 3.9.2 says this when passed a dict:

TypeError: Population must be a sequence.  For dicts or sets, use sorted(d).

And this solution does seem to work for both set and dict inputs.

Related