3

Many websites claim that the pop() method removes a random element from the set.

I'm confused because popping an element seems to be a deterministic process:

>>> {1,2,3,4,5}.pop()
1
>>> {1,2,3,4,5}.pop()
1
>>> {1,2,3,4,5}.pop()
1

This behaviour seems to be independent of the set contents

>>> {'a', type(2), (1)}.pop()
<class 'int'>
>>> {'a', type(2), (1)}.pop()
<class 'int'>
>>> {'a', type(2), (1)}.pop()
<class 'int'>

Why is this the case? How does pop() internally work? Is it incorrect to say that the pop() method is random?

martineau
  • 119,623
  • 25
  • 170
  • 301
Krish
  • 1,044
  • 9
  • 20
  • 8
    Don't use W3schools. It's terrible. Read the [actual docs](https://docs.python.org/3/library/stdtypes.html#frozenset.pop), which say it's an arbitrary element - there are no promises whatsoever about which element is picked. – user2357112 Nov 11 '20 at 07:47
  • 4
    It is allowed to be random. It is allowed to be deterministic. It is allowed to vary from machine to machine, or version to version, or implementation to implementation. Even if you look at the implementation, remember that that is only one implementation - everything might be totally different if you look again in a year, or if you look at PyPy or some other implementation. – user2357112 Nov 11 '20 at 07:50
  • Hmmm, that makes sense, I'd accept that if you wrote it up as an answer @user2357112supportsMonica – Krish Nov 11 '20 at 07:53
  • 1
    Also related: https://stackoverflow.com/questions/50963946/why-set-pop-return-first-element-while-list-pop-return-last-element-in-python, https://stackoverflow.com/questions/9848693/set-popping-python, https://stackoverflow.com/questions/12005436/python-sets-pop-behaviour – Tomerikoo Nov 11 '20 at 08:31

0 Answers0