How much memory does this byte string actually take up?

Viewed 382

My understanding is that os.urandom(size) outputs a random string of bytes of the given "size", but then:

import os
import sys

print(sys.getsizeof(os.urandom(42)))

>>>
75

Why is this not 42?

And a related question:

import base64
import binascii


print(sys.getsizeof(base64.b64encode(os.urandom(42))))
print(sys.getsizeof(binascii.hexlify(os.urandom(42))))

>>>
89
117

Why are these so different? Which encoding would be the most memory efficient way to store a string of bytes such as that given by os.urandom?

Edit: It seems like quite a stretch to say that this question is a duplicate of What is the difference between len() and sys.getsizeof() methods in python? My question is not about the difference between len() and getsizeof(). I was confused about the memory used by Python objects in general, which the answer to this question has clarified for me.

1 Answers
Related