{}const=>[]async()letfn</>var
DevelopmentBasics

7 ways to use underscores (_) in Python that almost nobody knows about

7 unexpected ways to use underscores in Python Underscores are not just part of variable names! In this article, we will tell you how to use it to improve code readability, create private variables, work with magic methods, and more.

К

Kodik

Author

3 min read

Many beginner Python programmers consider underscores (_) to be just part of variable names. But in fact, this symbol performs important and multifunctional tasks, especially in the hands of experienced developers 🧫🐍

Let's take a look 7 advanced uses of underscores in Pythonthat will surprise even those who have been writing code for years.


🔁 1. Getting the last calculated value in REPL

If you are working in an interactive shell Python (for example, in the terminal or Jupyter Notebook), the _ symbol allows you to get result of the last operation without saving it to a variable.

Example:

>>> 5 + 10
15
>>> _ * 2
30

Very convenient for quick calculations — no need to enter a new variable name every time ✨


🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

🖂 2. Placeholder variable in the loop

When the loop variable is not used in the body, you can substitute _ for it. This underlines: variable intentionally ignored.

Example:

for _ in range(3):
    print("Hi!")

Conclusion:

Привет!
Привет!
Привет!

This approach is often used when repeated actions, where the iteration index is not important.


💡 3. Separation of digits for readability

Large numbers are hard to read. In Python, you can visually separate numbers with underscores, without affecting the value.

Example:

сумма = 1_000_000  # the same as 1000000
print(сумма)

Conclusion:

1000000

Useful when working with finance 💸, science 🧪, or just for readability.


🔐 4. Internal variables and name mangling

Inside the classes, variables starting with a double underscore (__var), are considered private. Python automatically changes their name (name mangling) to make it difficult to access from the outside.

Example:

class Example:
    def __init__(self):
        self.__secret = "hidden"

    def reveal(self):
        return self.__secret

e = Example()
# print(e.__secret)  # Error!
print(e.reveal())     # works ✅

📌 Although you can bypass this restriction (e._Example__secret), doing so not recommended. This is an internal mechanism!


⚠️ 5. Resolving conflicts with keywords

If you need to use a variable name that matches a Python keyword (for example, class), add an underscore at the end.

Example:

def describe(class_):
    return f"This is class: {class_}"

print(describe("Python"))

Now class_ is a valid name, and you avoid conflicts with language syntax.


🔏 6. Private attributes in classes

In addition to paragraph 4: double underscore at the beginning of the attribute makes it "private". This not protection, but agreement for other developers: "Don't touch this unnecessarily."

Example:

class Hidden:
    def __init__(self):
        self.__data = "secret"

h = Hidden()
# print(h.__data)  # error
print(h._Hidden__data)  # will work, but you shouldn't do it

✨ 7. Magic (dunder) methods

Methods with double underscores on the edges (__method__) are magic methods, which determine the behavior of objects when interacting with the operator +, ==, print(), etc.

Example:

class Magic:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"Magic with the number {self.value}"

print(Magic(42))

Conclusion:

Magic с числом 42

🤹‍♀️ Useful cheat sheet on magic methods:

Method

What it does

__init__

Object initialization

__str__

Text representation (print())

__len__

Object length

__call__

Makes the object callable as a function

__getitem__

Access by index

__setitem__

Assignment by index

__contains__

Operator in

__eq__

Comparison ==

__add__

Addition +

__iter__

Makes the object iterable

🎯 These methods allow you to create own classes that behave like built-in types - beautiful, concise and powerful.


✅ Results

Underscoring in Python is not just syntax, and multifunctional tool:

  • helps to write cleaner and clearer

  • makes the code expressive

  • hides unnecessary information from the user

  • expands the capabilities of classes

Try using these techniques in your code, and you'll see how Python becomes even more powerful 💪🐍

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card