2

I know that in Java when continuously adding elements to an array, Java would use some strategy like: allocate a new RAM area with double space and copy the original array to the new area. What about Python3 (Now I'm using Jupyter Notebook, hence IPython intepreter)? How would Python manage the list space?

EDIT: To be specific, the Java ArrayList object

o_yeah
  • 688
  • 7
  • 17
  • 2
    A python list contains references to objects, so adding an element doesn't increase the list's own memory usage by much. In any case, the list has a certain growth space, and when that's used up, the references are copied to a new buffer with more growth space. That copying might be evident in careful timings, but otherwise it's not evident in normal use. There are so many other things going on when running code. – hpaulj Jul 04 '20 at 07:19
  • 1
    "I know that in Java when continuously adding elements to an array, Java would use some strategy like: allocate a new RAM area with double space and copy the original array to the new area." um, does it? What array methods are you talking about specifically? Do you mean *`ArrayList`* objects? In any case, methods that `.append` to a list will grow with amortized constant time, using a strategy like @hpaulj described. – juanpa.arrivillaga Jul 04 '20 at 07:30
  • 3
    https://rushter.com/blog/python-lists-and-tuples/ looks like a nice summary of list (and tuple) memory use, including the list resizing bit I described. That has a SO link, https://stackoverflow.com/questions/68630/are-tuples-more-efficient-than-lists-in-python/22140115#22140115 – hpaulj Jul 04 '20 at 07:31
  • 1
    Let's read the code: https://github.com/python/cpython/blob/d93605de7232da5e6a182fd1d5c220639e900159/Objects/listobject.c#L36 – Kedar.Aitawdekar Apr 19 '21 at 12:16

0 Answers0