0

Let's consider a simple situation,

var = 5
var = 6

The first line assign 5 to var and the next line re-assign 6 to var. Just out of curiosity, whether the value 5 would be automatically removed from the CPU's memory or not? If not, then would the following python code, in theory, blow up my computer due to memory comsuption?

var = 5
while True:
    var = var + 1
guorui
  • 871
  • 2
  • 9
  • 21
  • 3
    It's a lot more complicated than that -- no, Python doesn't allocate more memory for every reassignment, but at the same time, it also doesn't release memory back to the OS; it just frees up memory for *other uses inside the Python interpreter itself*. – Charles Duffy Jul 24 '19 at 03:49
  • 1
    There is garbage collection: https://en.wikipedia.org/wiki/Garbage_collection_(computer_science) – Klaus D. Jul 24 '19 at 03:50
  • 1
    https://rushter.com/blog/python-garbage-collector/ – GZ0 Jul 24 '19 at 03:52
  • Thank you all. According to the two links given above, I think the answer should lie in the mechanism of python's garbage collection. – guorui Jul 24 '19 at 08:09

2 Answers2

2

Yes, var is no longer keeping its previous value from being removed from memory at that point. In CPython (the usual implementation of Python):

  • that even usually happens as soon as you reassign var because CPython uses reference counting
  • that won’t happen for 5 specifically because CPython keeps a certain range of small integers in memory at all times

Your loop won’t fill up memory with old ints in any reasonable Python implementation. In practice, it uses a small, bounded amount of memory.

in theory

In theory, Python has arbitrary size ints, so you’ll use (for example) 2 GB of memory after 216,000,000,000 loop iterations. You’ll never come close to running out of memory for this reason, because there’s not enough time in the universe to get there.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

You would get integer overflow before consuming all your computer's memory if this example were done without Pure Python (e.g. Pandas/NumPy). Pure Python 3 has an int type that theoretically stores arbitrarily long integers; however there's still a limit on your computer's available memory. Python does the memory management in the background, and this reassignment doesn't hold onto the value 5 in memory after the variable is reassigned.

In essence:

var = 5 # var is 5 and its address is managed for you
var = 6 # the value that var points to is now 6, there's no record of 5 anymore.

so when you do the full loop:

var = 5
while True:
    var = var + 1 # This is reassignment of the value at the address -- NOT bloating memory
jsonV
  • 1,650
  • 2
  • 9
  • 23