Usage of the Underscore(_) in Python?

Usage of the Underscore(_) in Python?

Usage of underscore in Python

Soumendra kumar sahoo
·Jul 31, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • As a placeholder of variable
  • In object-oriented programming
  • Variable name delimiter
  • Access last executed result in command prompt
  • Separate digits for readability
  • Further reading

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
>>> _

ipython takes it to the next level with number-based access.


Separate digits for readability

>>> 1_00_000
>>> 3_25_50_000 == 32550000

Photo by the author.

Further reading

Did you find this article valuable?

Support Soumendra kumar sahoo by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this


Views are my own and not represent of my employer.
All articles and images are CC-BY-SA-4.0 licensed unless or until explicitly specified.