Suppose i create a large bytearray. Lets say 1000000 bytes or 1mb total. Does the interpreter reserve 1mb in memory or use memory as the byte array fills. Meaning does a mostly empty bytearray of 1000000 bytes used 1mb in memory?
2 Answers
sys.getsizeof returns the size of an object in bytes:
In [242]: sys.getsizeof(bytearray(10**6))
Out[242]: 1000025
So indeed bytearray(10**6) uses about 1MB of space.
Note that while sys.getsizeof gives an accurate answer for bytearrays, if applied to a container such as a list, it only gives the size of the container, not including the container's contents.
If you need to compute the size of an object including its contents, there is a recipe (referenced in the docs) for that.