6

I understand that Python lists are essentially C arrays, that they allocate a specific block of sequential memory; but, do these pieces of memory actually store the data that is in the list or do they simply point to another location in memory where the actual data is stored?

Does it perhaps depend on the size of the object stored in the list? As you could easily store a list of ints sequentially but it would be harder to dynamically store a variety of objects including self-defined objects.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0TTT0
  • 1,288
  • 1
  • 13
  • 23

2 Answers2

3

No, python lists store references ("pointers") to the objects

Performance Notes #

The list object consists of two internal parts; one object header, and one separately allocated array of object references. The latter is reallocated as necessary.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • Very logical decision. That's what I assumed without having seen any documentation stating one way or the other – 0TTT0 Nov 09 '17 at 00:55
1

An empty list in python takes 72 bytes, so consider this:

ls = [] takes 72 bytes

x = '1234567' takes 44 bytes

now, this:

[x] list contains the string x takes 124 bytes (72 + 8 + 44).

But, your question:

[x, x, x, x, x] A list that contains the string x 5 times takes 156 bytes (72 + 5 * 8 + 44).

Very nice explained here:

https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609

developer_hatch
  • 15,898
  • 3
  • 42
  • 75