0

I am puzzled with this statement that I got from an answer associated with this question:

"So tuples can store the elements directly inside the struct, lists on the other hand need a layer of indirection (it stores a pointer to the elements). This layer of indirection is a pointer, on 64bit systems that's 64bit, hence 8bytes."

  1. Is there really this difference among lists and tuples?

  2. What does exactly mean "store elements directly inside the structure"?

Yash
  • 3,438
  • 2
  • 17
  • 33
DanielTheRocketMan
  • 3,199
  • 5
  • 36
  • 65

2 Answers2

3

Everything in Python is an object. But containers don't store the object directly, they store a reference to the object - which is a C pointer.

A tuple can store those pointers directly because it's immutable, it never changes its size. The tuple object will be built large enough to contain all the pointers in an internal array.

Lists on the other hand can have elements added or deleted at any time. The array of pointers can't be self-contained, it must be indirectly accessed so that it can be re-allocated as needed.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1
  1. Yes!
  2. Store elements directly inside the structure means:

    References to objects are incorporated directly in a tuple object. In lists, this reference is incorporated by a pointer to it which doesn't change even when the value in reference changes.

Example:

# immutable integer 4
x = 4
#id() returns the memory address of the object.
print(x, id(x))
x = x+1
print(x, id(x))

lst = [[1],[2]]
print(lst, id(lst))
lst[0].append(2)
print(lst, id(lst))

#Output
4 139694701925760
5 139694701925792
[[1], [2]] 139694626834704
[[1, 2], [2]] 139694626834704

Here you can see that the reference of x changed because after addition, it referred to completely new address, whereas in the list the reference (pointer to the reference) remained same after the operation.

Yash
  • 3,438
  • 2
  • 17
  • 33