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
Effective Use of Underscores in Python: Tips and Tricks

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.

Pythonnaming-conventionscoding-tipsunderscoreData Handling
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login 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.