5

Why is the size of a set bigger than that of a dict?

s = set()
d = {}

for i in range(20):
    s.add(i)
    d[i] = 1

    print(f'{i+1}:', s.__sizeof__(), d.__sizeof__())

Output:

...
17: 712 624
18: 712 624
19: 2248 624
20: 2248 624

The 19th result confuses me.

NickS1
  • 496
  • 1
  • 6
  • 19
rocmon
  • 535
  • 4
  • 11
  • 6
    Related: https://stackoverflow.com/a/12477858/1490584 : `___sizeof___` returns the internal size in bytes for the given object. That probably just shows that Python pre-allocate different sizes for dict and set, and expand them via different rules. It might mean that Python leaves more empty space in sets and expands the container more greedily (for some or other performance reason due to some or other implementation). Why? I don't know. – Simon Streicher Oct 26 '20 at 08:04
  • https://stackoverflow.com/questions/56097997/how-does-python-implement-dictionaries – Nikaido Oct 26 '20 at 08:26
  • https://stackoverflow.com/questions/52377489/python-dictionary-and-set-memory-allocation/52377962 – Nikaido Oct 26 '20 at 08:26
  • 5
    While both ``set`` and ``dict`` roughly fall into the "hashtable" category, they are optimised for widely different use-cases. ``dict`` is intended for storage and retrieval, ``set`` is intended for set-operations such as unions, intersections and general membership. So the real question is: why do you think ``set`` should *not* be bigger? – MisterMiyagi Oct 26 '20 at 08:33
  • @SimonStreicher Interesting! You should have added that as an answer. It will be easy for many people to find it there. – Aniket Tiratkar Oct 26 '20 at 16:01
  • @AniketTiratkar I didn't answer the question, I only provided some pointer on why things doesn't always work out as expected, considering implementation detail. But I have no knowledge about the actual implementation. I think a combination of my comment with Nikaido's links and MisterMiyagi's comments would be far better as a answer. You are more than welcome to summarise the information into an answer if you want. – Simon Streicher Oct 27 '20 at 08:20

0 Answers0