How to understand the underscore better in Python

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,

Why do people use _ in for loops?
byu/Arnz_3 inlearnpython

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

 

Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

https://www.itersdesktop.com/author/nvntung/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.