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

陌路散爱 提交于 2020-08-10 00:44:20

问题


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:


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.



来源:https://stackoverflow.com/questions/50963946/why-set-pop-return-first-element-while-list-pop-return-last-element-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!