Role of Underscores ‘_’ in Python
The Underscore (_) is an eccentric character in Python. It can be used in many ways in a Python program.
The various uses of underscore (_) in Python are:
1) Use in Interpreter:
Python immediately saves the value of the last expression in the interpreter in this unique variable. Underscore (_) can also be used to value of any other variable.
Example 1:
Underscore (_) can be also be used as a normal variable.
Example 2:
Output:
10
2) Use in Loops:
In Python underscore (_) can be used as a variable in looping. It will access each element of the data structure.
Example 1:
Python3
Tuple = ( 50 , 40 , 30 )
for _ in range ( 3 ):
print ( Tuple [_])
|
Output:
50
40
30
Example 2:
Python3
List = [ 'Geeks' , 4 , 'Geeks!' ]
for _ in List :
print (_)
|
Output:
Geeks
4
Geeks!
3) Use in Ignoring Variables:
In Python underscore (_) is often used to ignore a value. If one doesn’t use some values when unpacking, just set the value to underscore (_). Ignoring involves assigning values to a particular vector underscore (_). We add values to underscore (_) if this is not used in future code.
Example 1:
Python3
p, _, r = 'Geeks' , 4 , 'Geeks!'
print (p, r)
|
Output:
Geeks Geeks!
Example 2:
Python3
p, q, * _, r = 'Geeks' , 4 , 'randomText' , 1234 , '3.14' , "Geeks!"
print (p, q, r)
print (_)
|
Output:
Geeks 4 Geeks!
['randomText', 1234, '3.14']
4) Separating digit of Numbers:
Underscores (_) can also be used to represent long digits number, it separates the group of digits for better understanding.
Python3
Crore = 10_00_000
print (Crore)
|
Output:
1000000
5) Use in Defining Access of Data members and Methods in Class:
Underscore (_) is used as a prefix for a method or data member in a class, defines its Access Specifier, and using double underscores (__) as both suffix and prefix refer to a Constructor.
Example 1:
Python3
class Gfg:
a = None
_b = None
__c = None
def __init__( self , a, b, c):
self .a = a
self ._b = b
self .__c = c
def __display( self ):
print ( self .a)
print ( self ._b)
print ( self .__c)
def accessPrivateMethod( self ):
self .__display()
Obj = Gfg( 'Geeks' , 4 , "Geeks!" )
Obj.accessPrivateMethod()
|
Output:
Geeks
4
Geeks!
Last Updated :
11 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...