pythonnoob
pythonnoob

Reputation: 69

How to understand the memories of list structure take in Python?

I want to know the memories of python take.

This is the code:

import sys
list1 = [1]
list2 = [1,2]
list3 = [1,2,3]
list4 = [1,2,3,4]
list5 = [1,2,3,4,5]
list6 = ['1',2,3,4,5,6]
list7 = [1,2,'3','4',5,6,7]
list8 = [1,2,3,'sdsd',5,6,7,8]
list9 = [1,2,3,4,5,6,7,8,9]

print('list1 size is :', sys.getsizeof(list1))
print('list2 size is :', sys.getsizeof(list2))
print('list3 size is :', sys.getsizeof(list3))
print('list4 size is :', sys.getsizeof(list4))
print('list5 size is :', sys.getsizeof(list5))
print('list6 size is :', sys.getsizeof(list6))
print('list7 size is :', sys.getsizeof(list7))
print('list8 size is :', sys.getsizeof(list8))
print('list9 size is :', sys.getsizeof(list9))

This is the result:

list1 size is : 64
list2 size is : 72
list3 size is : 120
list4 size is : 120
list5 size is : 120
list6 size is : 152
list7 size is : 120
list8 size is : 120
list9 size is : 152

My confused question is:

Thanks to all.

Upvotes: 3

Views: 108

Answers (1)

ParisNakitaKejser
ParisNakitaKejser

Reputation: 14839

First of all getsizeof are return the size in bytes.

So lets break it into smaller steps.

Code smaple for int, string + empty list:

import sys

list1 = [1]
list2 = ['a']
list3 = []

print('list 1:', sys.getsizeof(list1))
print('list 2:', sys.getsizeof(list2))
print('list 3:', sys.getsizeof(list3))

Response

list 1: 64
list 2: 64
list 3: 56

As you can see a empty list used 56 bytes and a list with a string or int use the same amount of bytes 64.

Every list area(step) will be reserved a 8 bytes amount min. to contain data look this exampel.

import sys

list1 = [1]
list2 = [1,2]
list3 = [1,2,3]
list4 = [1134,2234,3334]
list5 = ['ab','t',3334]

print('list 1:', sys.getsizeof(list1))
print('list 2:', sys.getsizeof(list2))
print('list 3:', sys.getsizeof(list3))
print('list 4:', sys.getsizeof(list4))
print('list 5:', sys.getsizeof(list5))

List 3-5 its used the same amount of space, the only equel here its the amount of list items.

list 1: 64
list 2: 72
list 3: 80
list 4: 80
list 5: 80

so why you see the bytes are equal I think you shut find in the way Python working, and its way its fundamental working.

I can't explain its more then this, about its logic or not its can always be discuss.

its the same if you save a text document on your computer its resevered some space for the file and the the real-byte size of the file its normal different, and I think python do something simialr.

Upvotes: 2

Related Questions