Why do tuples take less space in memory than lists?

前端 未结 4 1816
-上瘾入骨i
-上瘾入骨i 2020-12-04 09:52

A tuple takes less memory space in Python:

>>> a = (1,2,3)
>>> a.__sizeof__()
48

whereas lists

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 10:13

    MSeifert answer covers it broadly; to keep it simple you can think of:

    tuple is immutable. Once it set, you can't change it. So you know in advance how much memory you need to allocate for that object.

    list is mutable. You can add or remove items to or from it. It has to know the size of it (for internal impl.). It resizes as needed.

    There are no free meals - these capabilities comes with a cost. Hence the overhead in memory for lists.

提交回复
热议问题