Skip to content
Advertisement

python size of byte string in bytes

I’m confused as to why:

len(b'123') == 3
import sys
sys.getsizeof(b'123') == 36

What exactly is b'123'?

Advertisement

Answer

As @jonrsharpe has stated, b'123' is an immutable sequence of bytes, in this case of 3 bytes. Your confusion appears to be because len() and sys.getsizeof(b'123') are not the same thing.

len() queries for the number of items contained in a container. For a string that’s the number of characters, in your case you have 3 bytes, so its length will be 3.

Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

sys.getsizeof() on the other hand returns the memory size of the object, this means you are not only getting the size of the bytes, as it a full object it also has its methods, attributes, addresses… which are all considered in that size.

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement