最佳答案
So i was playing with list
objects and found little strange thing that if list
is created with list()
it uses more memory, than list comprehension? I'm using Python 3.5.2
In [1]: import sys
In [2]: a = list(range(100))
In [3]: sys.getsizeof(a)
Out[3]: 1008
In [4]: b = [i for i in range(100)]
In [5]: sys.getsizeof(b)
Out[5]: 912
In [6]: type(a) == type(b)
Out[6]: True
In [7]: a == b
Out[7]: True
In [8]: sys.getsizeof(list(b))
Out[8]: 1008
From the docs:
Lists may be constructed in several ways:
- Using a pair of square brackets to denote the empty list:
[]
- Using square brackets, separating items with commas:
[a]
,[a, b, c]
- Using a list comprehension:
[x for x in iterable]
- Using the type constructor:
list()
orlist(iterable)
But it seems that using list()
it uses more memory.
And as much list
is bigger, the gap increases.
Why this happens?
UPDATE #1
Test with Python 3.6.0b2:
Python 3.6.0b2 (default, Oct 11 2016, 11:52:53)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getsizeof(list(range(100)))
1008
>>> sys.getsizeof([i for i in range(100)])
912
UPDATE #2
Test with Python 2.7.12:
Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getsizeof(list(xrange(100)))
1016
>>> sys.getsizeof([i for i in xrange(100)])
920