By theory please correct me if I am wrong, it says that an int can take upto max 4 bits in case of number 9.

I haven't coded it low level languages but I assume that the datatype int in c and python shouldn't be different.

I want to know what is the reason that in Python an int is taking 24 bytes

Also if someone can explain how a bit/byte is calculated for a character.


>>> var = 1
>>> import sys
>>> print sys.getsizeof(var)
>>> var = 'Raheel'
>>> print sys.getsizeof(var)
>>> var = 2
>>> print sys.getsizeof(var)
>>> var = 'R'
>>> print sys.getsizeof(var)
  • 3
    It depends on the implementation. In CPython, all objects are actually C structs and contains much more stuff than just a single value. – Vincent Savard Feb 20 '18 at 16:29
  • 2
    What is "it" as in "it says that an int"... as it is not correct. Where are you getting this info? You should read this: docs.python.org/2/library/… – whatsisname Feb 20 '18 at 16:30
  • I was watching CS50 course on edx. I cannot provide a link here as it is not public page. – user212699 Feb 21 '18 at 3:53

The allocation unit cannot be smaller that 1 byte. For a 1-bit variable (a Boolean value) you have to allocate at least 8 bits, 7 of them unused.

A modern CPU operates on 64 bits (8 bytes), some on 32 bits = 4 bytes; 16-bit embedded controllers are common, 8-bit controllers are already rare. RAM also works more efficiently with larger widths, and normally expects alignment on 4-byte border for efficient fetches. This is why a 1-bit value can even take up 4 bytes in memory.

A Python integer is an object. Yes, you can invoke methods right on an integer constant: (1).__add__(2) or (100).bit_length(). This means that the actual integer value is stored along with a lot of other information.

Python integers try to adapt to the size of data, more so in Python 3 were an integer of any length is an object of the same type, just allocating enough bytes to store the value.

You can indeed pack values of small magnitude to more efficiently use the bits available. This is common is storage formats, especially where bandwidth is important. E.g. a GPU can work with textures packed in various ways, both as integers and (short) floats. Most modern CPUs have "vector instructions" to work with several independent 16-bit and 8-bit integers packed into 32- or 64-bit registers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy