Python Sys.getsizeof Method Returns Different Size Of Same Kind Of Lists
Solution 1:
Since your first list a
is defined from a literal, it is created with a size "to fit", while the second one b
is dynamically growing in runtime, enlarged at realtime to fit more elements before python knows there will be elements or not.
That is why you get different sizes.
Lists grow and shrink internally based on a number of factors. It is an implementation detail. As an example, in my CPyhton 3 implementation:
import sys
l = []
for x in range(10):
print(x, sys.getsizeof(l))
l.append(x)
The results:
0 64
1 96
2 96
3 96
4 96
5 128
6 128
7 128
8 128
9 192
As you can see the list is growing in size, but sometimes I get the same size in bytes, until it "grows" only in specific points. This is to save computing power growing once instead of growing on every increase.
Solution 2:
Python knows how long list a
will be, so it makes it exactly that long.
Python doesn't know exactly how long list b
will be, because map()
is lazy, so the list must grow as items are added to it. Memory allocation is relatively time-consuming, so when it needs more space, Python adds room for more items than you're adding to avoid having to allocate memory each time. This means there are often empty slots in dynamically-generated lists.
If those 24 bytes of memory are really important to you, you can simply instruct Python to make a copy of b
by slicing: b[:]
. Since Python knows how long b
is, the copy will have exactly that number of slots and take up the least amount of memory possible.
As nosklo notes, this behavior is an implementation detail.
Post a Comment for "Python Sys.getsizeof Method Returns Different Size Of Same Kind Of Lists"