0

I have looked at many other posts such as How is set() implemented? and What does hash do in python? and I would like some clarification of my understanding. So far sets use a hashtable, with the key as a member of the set. So lets say I had

set1 = {'s','t','v'}
's' in set1

returns true, but how this is done to my understanding everything in set1 has had a hash, so for example the dictionary could be dict['s'] = true, and to see if 's' in set1 is like checking dict['s'] and seeing if it is true or not. But my confusion comes from the fact that 's' will always have the same hash, which means if I had 2 sets, if set1 hashed 's' to being true, how does set2 hash 's' differently? Does every set have its own special hash function?

set1 = {'s','t'}
print('x' in set1)
print('s' in set1)
set2 = {'s'}
print('s' in set2)

Does set2 and set1 have different hashes for 's' when they are using the key as 's'.

Community
  • 1
  • 1
memelord23
  • 84
  • 1
  • 2
  • 11
  • 3
    No, the hash is the same. They are simply two separate hash tables. – kindall Jul 01 '16 at 01:44
  • 1
    Why do you think `s` needs two different hashes? – chepner Jul 01 '16 at 01:46
  • *attempts to thumbs up comment*, thanks :D – memelord23 Jul 01 '16 at 01:47
  • I thought that they went to the same hashtable :? – memelord23 Jul 01 '16 at 01:47
  • You can view hashes using the built-in `hash()` function; same string always returns same hash code. However `set1` and `set2` are different hashtables, different variables. – Xiaojun Chen Jul 01 '16 at 01:50
  • 1
    If you can read C you should take a look at the source for `set` and `dict`, which are really very similar. A set is essentially a `dict` with keys but no values. https://github.com/python/cpython/blob/master/Objects/setobject.c and https://github.com/python/cpython/blob/master/Objects/dictobject.c – PM 2Ring Jul 01 '16 at 01:52
  • I cannot read C, but what do you mean by keys with no values? Wouldnt you want to change the value from lets say, false to true, true meaning its in the set when checking the hashtable? – memelord23 Jul 01 '16 at 02:00
  • 1
    @MichaelCowie You don't need `false`, because the element simply doesn't exist in the set. – Barmar Jul 01 '16 at 02:35

0 Answers0