[Python-Dev] slightly inconsistent set/list pop behaviour (original) (raw)

John Barham jbarham at gmail.com
Wed Apr 8 08:13:19 CEST 2009


Tennessee Leeuwenburg wrote:

Now, I know that sets aren't ordered, but...

foo = set([1,2,3,4,5]) bar = [1,2,3,4,5] foo.pop() will reliably return 1 while bar.pop() will return 5 discuss :)

As designed.

If you play around a bit it becomes clear that what set.pop() returns is independent of the insertion order:

PythonWin 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on win32.

foo = set([5,4,3,2,1]) # Order reversed from above foo.pop() 1 foo = set([-1,0,1,2,3,4,5]) foo.pop() 0 foo = set([-1,1,2,3,4,5]) foo.pop() 1

As the documentation says (http://docs.python.org/library/stdtypes.html#set.pop) set.pop() is free to return an arbitrary element.

list.pop() however always returns the last element of the list, unless of course you specify some other index: http://docs.python.org/library/stdtypes.html#mutable-sequence-types, point 6.

John



More information about the Python-Dev mailing list