Table of Contents
Overview
The underscore or underbar (_) serves many purposes in Python, and I haven’t fully grasped about some aspects of every one of them before starting this article. I made assumptions, read inaccurate information, and even received an incomplete story from an online Python class I took. In this article, I’ll demonstrate the uses of the underscore and give you my very biased advice on how to treat it.
Using the underscore for __init__ or __name__
For example,
class Foo:
def __init__(bar, spam):
bar.spam = spam
def more_spam(bar):
bar.spam += 1
f = Foo(4)
Using the underscore as a temporary variable
Use it to ignore some returned or declared values
We can use the underscores for unpacking. For example, if we only care about 2 and 12 in the following expression.
_, _, x, y = 5, 7, 2, 12
I found a very fun thread on Reddit,
So many people are talking about useful things.
The underscore also works with Python Interpreter.
>>> 123 + 345 + 34 ** 2 1624 >>> _ + 1000 2624 >>>
Is the example above, we don’t need to type the returned value of the previous calculation. Using it in this context can understand that the returned value of the previous expression will be assigned in the underscore.
Use it in the loops
For example, we want to print a phrase for 5 times, we can use
for _ in range(5):
print("Hello World")
Also, we can print the index of a range using the underscore as follows.
for _ in range(5): print(_)
References
[1] https://www.datacamp.com/tutorial/role-underscore-python, accessed on 26th October 2025
