Mark Ransom Mark Ransom - 1 year ago 58
Python Question

Why does creating a list from a list make it larger?

I'm seeing some inconsistencies when using

on what should be identical lists. (Python 2.7.5)

>>> lst = [0,1,2,3,4,5,6,7,8,9]
>>> sys.getsizeof(lst)
>>> lst2 = list(lst)
>>> sys.getsizeof(lst2)
>>> lst3 = list(lst2)
>>> sys.getsizeof(lst3)
>>> sys.getsizeof(lst[:])
>>> sys.getsizeof(lst2[:])

Does anybody have a simple explanation?

Answer Source

With a list literal, the VM creates the list with a set length. When passing a sequence to the list() constructor the elements are added one by one (via list.extend()) and as such the list is resized when appropriate. Since the resize operation overallocates in order to amortize the cost, the final list will usually be larger than the source list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download