Open In App

Underscore (_) in Python

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, underscores have different meanings depending on how they are used. The single underscore (_) and double underscore (__) each serve specific purposes. They are commonly used in different situations, such as for variable names, method names, and more.

Single Underscore

Single underscore (_) in Python is used in various ways to improve code readability and organization. It can serve as a placeholder in loops, ignore specific values when unpacking, store the result of the last evaluated expression in the interactive shell, and indicate that a variable is intended for internal use within a class or module.

Example 1: Single Underscore In Interpreter

This code demonstrates the use of a single underscore (_) in the Python interactive shell:

Underscore (_) in Python
Single Underscore In Interpreter

Explanation:

  • Initially, the underscore (_) was used by itself, which resulted in a NameError because _ hasn't been assigned any value at that point.
  • After performing the operation a + b, the result 20 is stored in _ (since Python automatically assigns the result of the last operation to _ in the interactive shell).
  • The value of _ is then used in further calculations (_ * 2 and _ / 2).

Example 2: Single Underscore for ignoring values

This example demonstrates how the single underscore (_) is used to ignore values in Python, which is particularly useful when you don't need to use certain values in a loop or when unpacking a tuple/list.

Python
# Ignore a value of specific location/index
for _ in range(10):
    print ("Test")

# Ignore a value when unpacking
a,b,_,_ = my_method(var1)

Explanation:

  • The loop iterates 10 times, but the loop variable is ignored by using _. The underscore indicates that we don't need to use the loop variable itself, we just want the loop to run 10 times and print "Test" on each iteration.
  • my_method(var1) returns a tuple or list with multiple values. The underscore (_) is used to ignore specific values in the returned sequence. In this case, the third and fourth values are being ignored, and only a and b are assigned values.

Example 3: Single Underscore after a name 

Python has its own 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 

Python
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'>

Explanation:

  • The name class_ is used instead of class because class is a reserved keyword in Python, meaning it cannot be used as a variable or function name. By adding an underscore (class_), you avoid the conflict while still conveying that it represents a class.
  • The function my_definition() has two parameters: var1 (with a default value of 1) and class_ (with a default value of MyClass).
  • The function prints both the value of var1 and class_.

Example 4: Single Underscore before a name

This example demonstrates the use of a single underscore (_) before a variable or method name to indicate that it is intended to be private or for internal use only, though Python does not enforce strict privacy rules. It is just a convention to signal that a variable should not be accessed directly outside the class.

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

print(test.public)

print(test._private)

Output
10
12

Explanation:

  • self.public = 10 is a regular public attribute. It can be accessed directly from outside the class.
  • self._private = 12 is intended to be a "private" attribute. The single underscore before the name _private is a convention to indicate that this variable should not be accessed directly from outside the class.
  • test.public is accessed directly, and Python allows this because it is a public attribute.
  • test._private is also accessible, even though the underscore suggests it should not be accessed directly.

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.

Python
# 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

Double underscore

In Python, a double underscore (__) before a variable or method name has a special significance. It is commonly used for name mangling, a technique that helps avoid conflicts in subclass inheritance.

Example 1: Double Underscore before a name

The leading double underscore tells the Python interpreter to rewrite the name in order to avoid conflict in a subclass. Interpreter changes variable name with class extension and that feature known as the Mangling. 

Python
class Myclass():
    def __init__(self):
        self.__variable = 10

Calling from Interpreter

Underscore (_) in Python
testFile.py 

The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.

Python
class Myclass():
    def __init__(self):
        self.__variable = 10

    def func(self)
    print(self.__variable)

Calling from Interpreter

Underscore (_) in Python

Example 2: Double underscore before and after a name

The name starts with __ and ends with the same considering special methods in Python. Python provides these methods to use as the operator overloading depending on the user. Python provides this convention to differentiate between the user-defined function with the module's function 

Python
class Myclass():
    def __add__(self,a,b):
        print (a*b)

Calling from Interpreter

Underscore (_) in Python

Next Article
Article Tags :
Practice Tags :

Similar Reads