Skip to content
Effective Use of Underscores in Python: Tips and Tricks
Fundamentals 3 min read

Effective Use of Underscores in Python: Tips and Tricks

This article explains how the underscore character in Python can be leveraged for quick console result reuse, selective tuple unpacking, protected and private attribute naming, and numeric readability, providing practical code examples that illustrate each technique for more efficient and readable code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle

In Python, the underscore "_" serves multiple practical purposes that can streamline coding and data handling.

When working in the interactive console, "_" automatically stores the result of the last expression, allowing quick reuse without re‑typing.

# 忽略不需要的返回值

def fetch_data():
    return 1, 'Alice', 'Data'

_, name, _ = fetch_data()
print(name)

Underscores can also be used to ignore unwanted values when unpacking tuples or function returns, focusing only on needed items.

class Car:
    def __init__(self):
        self._speed = 0  # 受保护的属性
        self.__name = None  # 私有属性

    def _increase_speed(self):
        # 不建议外部直接调用
        self._speed += 10

Following naming conventions, a single leading underscore marks protected attributes, while double leading underscores trigger name‑mangling for private attributes, helping define clear APIs.

For large numbers, inserting underscores as visual separators improves readability, especially in financial or scientific calculations.

Mastering these underscore techniques enhances code clarity, efficiency, and professionalism in Python projects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonnaming conventionsCoding Tipsunderscoredata handling
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.