Usage of the Underscore (_) in Python
2 min readSep 2, 2021
Do you know all the usage of the Underscore in Python?
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.
1. 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.
2. Underscore 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…