Equal sets with unequal print and str() representations

Westley Martínez anikom15 at gmail.com
Mon Oct 17 12:29:39 EDT 2011


On Sun, Oct 16, 2011 at 05:52:03PM -0600, Ganesh Gopalakrishnan wrote:
> 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

This is because sets do not preserve order.



More information about the Python-list mailing list