V
V
Viktor Shubin2018-09-23 11:11:27
Python
Viktor Shubin, 2018-09-23 11:11:27

How are numbers stored in python?

I got acquainted with ASCII and with utf-8 and unicode, but I still have two points that I can’t understand in any way ... I seem to have already re-read many articles on this topic. Everywhere it is said about how characters are stored in memory, but nowhere is it said how integers or real numbers are stored in memory?
And secondly, I don’t understand in any way, if I work in the pycharm interpreter, then in what encoding do they give me characters there? It's just that Russian letters weigh two bytes in utf-8, but when I request len('zh') it gives me one byte (so in what encoding does it give me characters and a string ???), maybe I'm not catching up with something ...
Right away I will mark the received answer if the answer is given to my question! Thanks...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-09-23
@ViktorS88

As Roman Kitaev already noted , the function len()returns the number of elements in the container, in your case, the characters in the string, and not the number of bytes occupied by the container in memory. To get the size in bytes, you can use the getsizeof() function of the module sys. And then a surprise awaits you

In [1]: import sys

In [2]: sys.getsizeof('ж')
Out[2]: 76

The character 'zh' occupies not one or two bytes, but 76. This is explained by the fact that absolutely everything in Python is an object. In this case, 76 bytes are occupied by a string object consisting of one character. At the level of a virtual machine, objects are ordinary Cish structures containing data and a number of service fields. In particular, the line looks something like this:
typedef struct {
    long ob_refcnt;
    PyTypeObject *ob_type;
    size_t ob_size;

    long ob_shash;
    int ob_sstate;
    char ob_sval[1];
} PyStringObject;

and the integer is
typedef struct {
    long ob_refcnt;
    PyTypeObject *ob_type;
    size_t ob_size;

    long ob_digit[1];
} PyLongObject;

The topic of memory management in Python is very deep, but as sim3x rightly pointed out , it can be confusing for a beginner.

R
Roman Kitaev, 2018-09-23
@deliro

Better than this, no one will say
https://github.com/python/cpython/blob/master/Obje...
len("w") shows the length of the string (number of characters), not how much memory it takes in bytes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question