Is it a bad practice to reuse a repeat variable multiple times in a given script?

Is it a bad practice to reuse the same variable name to repeat for several for-loops in a given script?

For instance,

for url in urls1: print url for url in urls2: print url for url in urls3: print url 

I know that the url variable is not limited in scope to the for loop, so there is the potential to use the url variable outside the for loop to become messy and harder to understand. But I'm curious if there is a β€œbest” practice? Should I use conventions like "url1", "url2"? Or am I overdoing it, and is that all that works to make it easier to understand?

+6
source share
4 answers

A good variable name is one that helps the program understand (and does not conflict with a reserved or known name). The answers will probably only be subjective, but I would say that as long as the variable name you use means the same thing in all for loops, this is normal.

The scope of the variable is really not limited to the for loop, but the value will be overwritten during the first iteration of the next loop of the loop. On the contrary, such a code would be nasty:

 for url1 in urls1: print url1 for url2 in urls2: print url1, url2 
+3
source

I think it all depends on the context. For example, in your case, you could write this as:

 for url in urls1+urls2+urls3: print url 

But your example is for demonstration. If it's just a loop variable that you want to use for iteration, I don't see any problem when reusing the same loop variable multiple times. On the other hand, if that makes sense, you can also choose a context-sensitive name for each iteration. For instance:

 for base_url in urls: .... for dev_url in urls: ... 
+2
source

If you really have a lot of lines of code inside your loops, where you do a lot of operations with the iteration variable, it might be a good idea to give it a unique, meaningful name, especially if different loops repeat on different types of objects,

In other cases, as in the example you specified, the iteration variable in different loops represents the same object and gives the same name, improving the readability of the code.

So, in general, you should find a way to make your code the most readable.

+1
source

The variable must be readable by code. This code will work fine regardless of the variable name. I want to point to the edge register that I come across from time to time, strictly in python 2.7.

Using list comprehension in python 2.7 eliminates the name of the target variable. For example

 x = 'before' a = [x for x in 1, 2, 3] print x # this prints '3', not 'before' 

I am to blame for such things, so I try to keep the variables unique. This bug / function has been fixed / changed in python3.

Link

+1
source

All Articles