Single Underscore

Example 1: Single Underscore In Interpreter:

 _ returns the value of the last executed expression value in Python Prompt/Interpreter 

 

Example 2: Single Underscore for ignoring values

Multiple times we do not want return values at that time to assign those values to Underscore. It is used as a throw-away variable. 

Python3




# Ignore a value of specific location/index
for _ in range(10)
    print ("Test")
 
# Ignore a value when unpacking
a,b,_,_ = my_method(var1)


Example 3: Single Underscore after a name 

Python has theirs by default keywords which we can not use as the variable name. To avoid such conflict between python keyword and variable we use underscore after the name 

Python3




class MyClass():
    def __init__(self):
        print("OWK")
 
 
def my_definition(var1=1, class_=MyClass):
    print(var1)
    print(class_)
 
 
my_definition()


Output:

1
<class '__main__.MyClass'>

Example 4: Single Underscore before a name

Leading Underscore before variable/function /method name indicates to the programmer that It is for internal use only, that can be modified whenever the class wants. Here name prefix by an underscore is treated as non-public. If specify from Import * all the names starting with _ will not import. Python does not specify truly private so this one can be called directly from other modules if it is specified in __all__, We also call it weak Private 

Python3




class Prefix:
    def __init__(self):
        self.public = 10
        self._private = 12
test = Prefix()
 
print(test.public)
 
print(test._private)


10
12

Example 5: Single underscore in numeric literals

The Python syntax is utilized such that underscores can be used as visual separators for digit grouping reasons to boost readability. This is a typical feature of most current languages and can aid in the readability of long literals, or literals whose value should clearly separated into portions.

Python3




# grouping decimal for easy readability of long literals
amount = 10_000_000.0
 
# grouping hexadecimal for easy readability of long literals
addr = 0xCAFE_F00D
 
# grouping bits  for easy readability of long literals
flags = 0b_0011_1111_0100_1110


Underscore (_) in Python

In this article, we are going to see Underscore (_) in Python.

Following are different places where “_” is used in Python:

  • Single Underscore:
    • Single Underscore in Interpreter
    • Single Underscore after a name
    • Single Underscore before a name
    • Single underscore in numeric literals
  • Double Underscore:
    • Double underscore before a name
    • Double underscore before and after a name

Similar Reads

Single Underscore

Example 1: Single Underscore In Interpreter:...

Double underscore before a name

...

Double underscore before and after a name

...

Contact Us