Do you know all the usage of the Underscore in Python?

Do you know all the usage of the Underscore in Python?

Usage of underscore in Python

Subscribe to my newsletter and never miss my upcoming articles

This is a continued story of my previous post Star in Python.

In this article, we will know about the usage of underscore in Python.

As a placeholder of variable

If you do not use a variable then you can name it as underscore.

>>> my_dict = {'a': 1, 'b': 2}
>>> for k, _ in my_dict.items():
...    print(f"The keys are: {k}")
The keys are: a
The keys are: b

Here we have not used the values of the dictionary therefore no need to assign that to a named variable, underscore we have used to denote the values of the dictionary. This is a best practice.
Although this is not such an excellent example, hope you got the point.

In object-oriented programming

Underscore plays a significant part in OOP.

Private method

To define a private method _ prefix is used.


>>> class myClass:
...    def _my_private_method(self):
...    pass

Protected method

>>> class myClass:
...    def __my_protected_method(self):
...    pass

Dunder method

To define in-built under methods

>>> class myClass:
...    def __init__(self):
...    pass

Variable name delimiter

Under PEP8 guideline variable names should be delimited with underscores.

Access last executed result in command prompt

In the terminal or command prompt to access the last output of the operation you can use the underscore.

>>> 4 + 3
7
>>> _
7

Separate digits for readability

>>> 1_00_000
100000
>>> 3_25_50_000 == 32550000
True

Photo by the author.

Further reading

 
Share this