3

It's a little bit confusing. Is it actually comes from stack pop/push terminology?

L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.

>>> [1,2].pop()
2

Remove and return an arbitrary set element. Raises KeyError if the set is empty.

>>> {1,2}.pop()
1

1 Answer 1

3

set.pop does not return the first element. As it clearly says in the help that you quoted, it returns an arbitrary element.

And the reason for this is simple: sets are inherently unordered. There is no meaningful "first" or "last" element.1

1. Since sets are stored as hash tables, it makes sense for both performance reasons and simplicity reasons that set.pop will remove the first element in the hash table, which will often be the same as the first element iterated by the set, but that's not guaranteed. And, in fact, exactly when it's true is different in CPython 3.6 - 3.7 than in 3.3 - 3.5.

Sign up to request clarification or add additional context in comments.

2 Comments

@MohanBabu Actually, forget the example I linked (which depends on your Python implementation/version and random chance); that was silly. Just consider {2, 'a'}. That set has no smallest value, and yet pop works just fine.
agree @abarnert

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.