+ 4
When to use _ with for ?
When should we use _ with for ? Eg. for _ in range(N) What this line will do ? I know normal for loop syntax and range function.
4 Réponses
+ 1
_ can be used in the case where you don't need to use the loop variable inside the loop
+ 1
_ is a valid variable name identifier: you could use it for what you want ^^
Anyway, it's kind of convention widely shared (beyond just only Python community) to use it for variables needed syntaxically but not technically used... ;)
+ 1
This is what I learned from YouTube. Underscore can be used in these many ways.
Case 1: For storing the result of the last executed expression in an interactive shell. The Python interpreter stores the last expression value to the special variable called '_'.
Eg.: >>> 1+2+3
Output: 6
>>> _
Output: 6
>>>_ + 6
Output: 12
>>>_
Output: 12
---------------------------------------------
Case 2: The underscore is also used for ignoring specific values. If you don't need the specific values, just assign the values to underscore.
Eg 1.: for x in range(10):
print("Hi")
Here variable 'x' is of no use, so u can replace it with underscore.
for _ in range(10):
print("Hi")
Eg 2.: x,_,z = [1,2,3]
Here 1 and 3 will be assigned to x and z respectively.
----------------------------------------------
Case 3: Single leading underscore gives variables and functions special meaning. This convention is used for declaring private variables, functions & classes in a module. Anything with this convention are ignored when you try to import your module in some other module by
from module import *
However, if you still need to import a private variable or function, import it directly.
----------------------------------------------
Case 4: It is used for separating digits of numbers for readability. In general, we use ','. In Python we can use '_'.
Eg.: x = 1_234_567
print(x)
Output: 1234567
---------------------------------------------
Case 5: Double leading underscore will change the way a method/attribute can be called using an object of a class. This convention is useful in case of inheritence when you want to use methods of same name in child & parent class separately.
Eg.:
class A:
def __double_method(self):
print("A")
a = A()
a.__double_method() #this will not work
a._A__double_method() #this will work
Lets make another class B
class B(A):
def __double_method(self):
print("B")
b = B()
b._B__double_method()
b._A__double_method()
Output: B
A