Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most Pythonic way to pop a random element from a set in Python3.6+?

Tags:

Before 3.6 I would simply use set.pop(). Now, sets are ordered and pop always removes from the start.

What do you think is the most pythonic way?

I'm not sure how I feel about set.remove(random.sample(set, 1)[0]).

like image 790
Hélio Meira Lins Avatar asked Jun 17 '17 13:06

Hélio Meira Lins


People also ask

How do you pop a random element from a set in Python?

The set pop() is a built-in Python method that removes the random element from the set and returns the removed element. The pop() method does not pop from the back or front; it can pop any element from anywhere present in the set. Unlike the stack, a random element is popped off the set.

How can you pick a random item from a range in Python?

Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

How do you select multiple random items from a list in Python?

Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.


1 Answers

The set .pop() method does not accept a parameter, it removes an arbitrary (but not random) set value. https://docs.python.org/3.6/library/stdtypes.html#set.pop

Take a set sample with one element random.sample(s, 1) and use set.remove().

>>> s = set([1,2,3,4,5]) >>> el = random.sample(s, 1)[0] >>> s.remove(el) >>> print(s) {1, 3, 4, 5} 

The random.choice does not work because sets are not indexed.

>>> random.choice(s) Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/usr/lib/python3.5/random.py", line 256, in choice     return seq[i] 
like image 193
iurisilvio Avatar answered Sep 24 '22 09:09

iurisilvio