Sitemap

Use of Underscore in Python

2 min readNov 10, 2021

--

Python

If you are a python programmer, you must have heard about underscore. Python works with two type of underscore:

  1. single underscore ( _ )

2. double underscore ( __ )

It is a very powerful syntax, so in this article I am going to discuss 5 use of underscore.

1. In Interpreter:

It returns the last executed expression value in the python interpreter.

>>> val1 = 10

>>> val2 = 10

>>> _

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name '_' is not defined

>>> val1+val2

20

>>> _

20

>>> _ * 6

120

>>> _

120

>>> _ / 2

60

Get Vipul Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

2. With the For loops

we don’t need an variable to traverse the for loop. We can access the each value by underscore.

L = ["Some", 4, "value"]
for _ in L:
print(_)
Output:
Some
4
value
-----------------------------------------
Tuple = (10,20,30)
for _ in range(len(Tuple)):
print(Tuple[_])
Output:
10
20
30

3. Use in Ignoring the variables:

It is used to ignore the value, If someone doesn’t want to use some value while unpacking, just set the values to underscore ( _ ). We add values to underscore, if this is not used in the future code.

a, _, c = 'Blogs', 10, 'Django'
print(a, c)
Output:
Blogs Django
p, q, *_, r = "Python", 4, "Django", 1234, '3.14', "Flask"
print(p,q,r)
output:Python 4 Flaskprint(_)
output:['Django', 1234, '3.14']

4. Seperation of digits of Big number:

Underscores (_) can also be used to represent long digits number, it separates the group of digits for better understanding.

# Seperating digit of numbers
crore = 10_00_000
print(crore)
Output:
1000000

5.Define access of data members and methods:

We can access the _ and __ variable via methods in the class.

class Lang:
a = None
_b = None
__c = None

def __init__(self,a,b,c):
# Public
self.a = a

# Protected
self._b = b

# Private
self.__c = c

# Private Method
def __display(self):
print(self.a)
print(self._b)
print(self.__c)

# Public Method
def accessPrivateMethod(self):
self.__display()

obj = Lang("Django", 4, "Python")
obj.accessPrivateMethod()
print(obj._b)

Output:
Django 4 Python
4

Conclusion:

In this article, we have discussed the use of undescore in some cases, I will try to explore more on this in next article.

I hope you have enjoyed the article.

--

--