Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing variables in Python

Tags:

python

In Python, I often reuse variables in manner analogous to this:

files = files[:batch_size]

I like this technique because it helps me cut on the number of variables I need to track.

Never had any problems but I am wondering if I am missing potential downsides e.g. performance etc.

like image 288
jldupont Avatar asked Jan 29 '12 16:01

jldupont


People also ask

Can I reuse variables in Python?

In Python, we may reuse the same variable to store values of any type. A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old.

Can variables be reused?

It is better to reuse variables in terms of memory. But be careful you don't need the value in a variable before reusing it. Other than that, you shouldn't use always the variable. It is important to keep a clean and readable code.

Can you reuse variable names in different functions?

Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes. Save this answer.


1 Answers

There is no technical downside to reusing variable names. However, if you reuse a variable and change its "purpose", that may confuse others reading your code (especially if they miss the reassignment).

In the example you've provided, though, realize that you are actually spawning an entirely new list when you splice. Until the GC collects the old copy of that list, that list will be stored in memory twice (except what you spliced out). An alternative is to iterate over that list and stop when you reach the batch_sizeth element, instead of finishing the list, or even more succinctly, del files[batch_size:].

like image 151
cheeken Avatar answered Nov 06 '22 12:11

cheeken