0

I have code like:

While 1:
    A = input()
    print A

How long can I expect this to run? How many times?

Is there a way I can just throw away whatever I have in A once I have printed it?

How does python deal with it? Will the program crash after a while?

Thank you.

  • 2
    This is called garbage collection and is done by the python interpreter for you. – filmor Feb 24 '14 at 20:42
  • unrelated: you could use `from IPython import embed; embed()` to get `ipython` shell (it looks like your loop tries to emulate Python shell). – jfs Feb 24 '14 at 20:46
  • @J.F.Sebastian Where does that come from?! It’s just a loop that happens to print the input. – poke Feb 24 '14 at 20:54
  • @poke: `input(prompt)` in Python 2 is equivalent to `eval(raw_input(prompt))` (meaning that you can put there any Python expression) – jfs Feb 24 '14 at 20:55
  • @J.F.Sebastian You are restricted to expressions though, so it’s not the same. And I personally always assume that people post simplified examples here, so that’s probably not all what OP’s doing anyway. Emulating the interpreter is a bit overinterpreted in this case imo. – poke Feb 24 '14 at 21:02

3 Answers3

2

When you reassign A to a new value, there is nothing left referring to the old value. Garbage collection comes into play here, and the old object is automatically returned back to free memory.

Thus you should never run out of memory with a simple loop like this.

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    in theory. In practice some memory may be never released e.g., ["Unfortunately, that free list is both immortal and unbounded in size."](http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm) – jfs Feb 24 '14 at 20:50
1

This can literally run forever. The Python garbage collector will free the memory used by A when it's value is overwritten.

Side note: "While" must be lowercase "while" and it is considered more Pythonic to have "while True:" instead of "while 1:"

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
0

You change the value of A so memory wouldn't be an issue as python garbage collects the old value and returns the memory... so forever

DeadChex
  • 4,379
  • 1
  • 27
  • 34