Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why set pop return first element while list pop return last element in python

Tags:

python

stack

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
like image 282
Daniil Mashkin Avatar asked May 13 '26 21:05

Daniil Mashkin


1 Answers

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.

like image 55
abarnert Avatar answered May 16 '26 09:05

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!