6

I'm new to python.To find the sizeof an integer i used getsizeof method available in sys module. It returns 24 bytes for integer and 34 bytes for char.

>>> sys.getsizeof(1)
24
>>> sys.getsizeof('a')
34

I feel this size (24 bytes or 34 bytes) is very large to hold an integer or char... I feel that memory is getting wasted much.. Could you please help me in understanding the concept behind this memory management in python.

1
  • 5
    'a' is a string, not a char. Commented Jul 10, 2011 at 8:57

2 Answers 2

15

Because everything is an object, everything has an object bookkeeping overhead. In CPython, it's at least size of a type pointer and reference count for every object. Plus whatever specific objects need for their data. And there's also garbage collector overhead for some objects. Certainly nothing is 'wasted', it's a silly idea.

And there is no char in Python, 'a' is a string of length 1.

Sign up to request clarification or add additional context in comments.

3 Comments

+1: Excellent answer. See also dir(1) and dir('a') to get a feel for what these objects can do.
@Johnsyweb: To be fair, most if not all of those entries are methods which aren't part of the object but of the class (and therefore not counted into the size of the individual object).
@delnan: True enough, but it highlights that these are not just an int or a "char".
2

Every time you define an object in Python, you’ll create a new object with a new identity.

But there are some exceptions for small integers (between -5 and 256) and small strings (interned strings, with a special length (usually less than 20 character)) which are singletons and have same id (actually one object with multiple pointer).

Examples: In [1]: L1 = [1, 2, 3]

In [2]: L2 = [1, 2, 3]

In [3]: id(L1) Out[3]: 4436443080

In [4]: id(L2) Out[4]: 4436349576

Example 2: In [5]: a = 10

In [6]: b = 10

In [7]: id(a) Out[7]: 4401921584

In [8]: id(b) Out[8]: 4401921584

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.