On Fri, Dec 07, 2018 at 05:59:22PM +0000, Alan Gauld via Tutor wrote: [...] > > ... In languages without garbage collection, reusing > > the same name, like "index" repeatedly might save some > > small amount of space. > > Garbage collection only helps if the variable loses > its assignment. If the variable retains its value it > won't be garbage collected. So the same space saving applies. > > However it is very rare that Python is used in the kind > of scenarios where that kind of space saving is > significant (usually embedded controllers with > tiny memory spaces).
People routinely use Python with seriously large amounts of data, hundreds of megabytes or even gigabytes, and freely make copies of it, secure in the knowledge that they don't have to do much to manage memory because the garbage collector will do so for them. Consider a simple expression like: text = '"' + (text.strip().lower().replace(',', ' ')) + '"' That makes five slightly-modified copies of the original text. And that's just from a single short expression. Memory is cheap, but not so cheap that we can afford to keep around hundreds of redundant copies of large objects. Generally speaking, we can afford to be profligate with copies of objects because we know they won't "leak" and survive for very long: at worst, they will be reclaimed when the current function returns. The only times we need worry about lifetimes of objects are when we are working in the global scope, or when adding attributes to long-lived objects. Regardless of whether we write the above as a single expression, or split it over many lines: text = text.strip() text = text.lower() text = text.replace(',', ' ') text = '"' + text text = text + '"' the result will be the same. And I don't think the above would be more understandable if we invented separate names for each of the intermediate results. -- Steve _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor