Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a discrepancy in memory size with these 3 ways of creating a list? [duplicate]

sys.getsizeof(list(range(10))) # 200
sys.getsizeof([0,1,2,3,4,5,6,7,8,9]) # 144
sys.getsizeof([i for i in range(10)]) # 192

I have very little C experience so this may be over my head, but I am curious as I am playing around with sys.getsizeof.

I tried to look at the documentation but I only found this:

getsizeof() calls the object’s sizeof method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

Due to my very little C experience I am not too familiar with GC as well but from my Python-related GC readings, I understand that only references are counted in Python. In the above situation, we aren't saving it to a variable so I am assuming no GC references?

like image 559
Moondra Avatar asked Apr 12 '19 18:04

Moondra


Video Answer


1 Answers

It appears that python allocates some additional memory when using the list() and range() functions. If you copy the values from the generated arrays to a new array using [:] you can see that they become equal.

Example:

import sys

sys.getsizeof(list(range(10))[:]) # 144
sys.getsizeof([0,1,2,3,4,5,6,7,8,9][:]) # 144
sys.getsizeof([i for i in range(10)][:]) # 144
like image 167
DobromirM Avatar answered Sep 30 '22 06:09

DobromirM