简体   繁体   中英

Python list I don't know why the difference is 16

>>> import sys
>>> print(sys.getsizeof(int()))
12
>>> print(sys.getsizeof(str()))
25
>>> mylist = [1,2,3,4,5,'ab']
>>> print(id(mylist))
50204144
>>> print(id(mylist[0]))
1849873456
>>> print(id(mylist[1]))
1849873472
>>> print(id(mylist[2]))
1849873488
>>> print(id(mylist[3]))
1849873504
>>> print(id(mylist[4]))
1849873520
>>> print(id(mylist[5]))
50209152

I don't know why the difference is 16:

64-bit operating system

因为它们是列表中的int ,所以整数在内存中的位置是16 到 16位,我真的建议您查看这篇文章: id() 函数用于什么?

It looks like your question is: If sys.getsizeof(int()) is 12, then why are some of the the id() values 16 bytes apart instead of 12?

And it looks like you are expecting newly allocated int s to be 12 bytes away from one another because an int takes 12 bytes of storage.

If you are expecting that, it is because you are expecting a Python list to be like a C array, a chunk of contiguous memory where an array of five 8-byte objects takes exactly 40 bytes. But Python lists are not arrays, and list elements are not necessarily allocated in ascending memory order (let alone packed together). And so you can't expect the values of id() to be predictable from the amount of memory the object takes up.

By all means learn about the way Python's data structures are really allocated, if that really interests you. But it is a topic so advanced that few outside the CPython core team ever need to think about it. The rest of us are just content that it works. Which is why you are getting comments like it's an implementation detail and why do you care?

It is important to know how a C array is allocated because in C you manipulate memory pointers directly and getting that wrong can be catastrophic. But Python takes care of memory allocation for you, so knowing all the details of how it works is unlikely to make you a better Python programmer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM