Equal sets with unequal print and str() representations
This probably is known, but a potential pitfall (was, for me) nevertheless. I suspect it is due to hash collisions between 's3' and 's13' in this case? It happens only rarely, depending on the contents of the set. >>> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} >>> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} >>> S1 S1 {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} >>> S2 S2 {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} >>> S1==S2 S1==S2 True >>> str(S1) str(S1) "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" >>> str(S2) str(S2) "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" >>> str(S1) == str(S2) False -- Ganesh -- http://mail.python.org/mailman/listinfo/python-list
Re: Equal sets with unequal print and str() representations
Thanks to all who replied - also to Ben. I had foolishly assumed that the same set exhibits the same rep on at least one platform. Like any bug, the falsity of my assumption took months to expose - till then, things had worked fine. Needless to say I'm new to Python. (The double printing is because I tend to work within an Emacs inferior shell.) Cheers, Ganesh On 10/16/11 8:23 PM, Ben Finney wrote: Ganesh Gopalakrishnan writes: This probably is known, but a potential pitfall (was, for me) nevertheless. I suspect it is due to hash collisions between 's3' and 's13' in this case? What is the actual problem? What behaviour is occurring that doesn't match your expectation? S1==S2 S1==S2 True str(S1) str(S1) "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" str(S2) str(S2) "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" str(S1) == str(S2) False Right, that's all correct (though I don't know why some of your expressions are being shown twice). A deliberate property of a set is that its items are unordered. http://docs.python.org/library/stdtypes.html#set> Since sets are unordered, the string representation may show the items in an arbitrary and unpredictable sequence. Don't write any code that depends on a predictable sequence of retrieval from an unordered collection. So what did you expect instead, and what supports that expectation? -- http://mail.python.org/mailman/listinfo/python-list