Skip to content Skip to sidebar Skip to footer

Python: .pop() On Unordered Sets

I have a question regarding the .pop() method. In the documentation, it states that on sets: Remove and return an arbitrary element from the set. So what exactly does 'arbitrary'

Solution 1:

No.

"Arbitrary" means the implementation returns whichever element is most convenient. You are not guaranteed randomness. Use random.sample() or random.shuffle() if you need random selection.

Solution 2:

I think the best way would be to use random.shuffle

>>> import random
>>> li = ["bob", "rachel", "sara", "david"]
>>> random.shuffle(li)
>>> li
['sara', 'bob', 'david', 'rachel']

If you want to get the elements one by one, you can then use li.pop().

Post a Comment for "Python: .pop() On Unordered Sets"