When is a variable released from memory?
Question: Say I define a function, which builds a list, and then prints the items of the
list one by one (no practical use, just an example:

    
    
    import os
    
    def build_and_print():
        thingy = os.walk('some directory')
        for i in thingy:
            print i
    
    if __name__ == '__main__:
        build_and_print()
    

If the `thingy` that is built is very large it could take up a lot of memory,
at what point will it be released from memory?

Does python store the variable `thingy` until the script is finished running
or until the function that builds/uses it is finished running?


Answer: Once a Variable goes **out of scope** , it is collected by the garbage
collector.

You can see the collector [code
here.](https://hg.python.org/cpython/file/tip/Modules/gcmodule.c) Go to
collect function, there comments explain the process well.

