Coding Nexus

Coding Nexus is a community of developers, tech enthusiasts, and aspiring coders. Whether you’re exploring the depths of Python, diving into data science, mastering web development, or staying updated on the latest trends in AI, Coding Nexus has something for you.

Follow publication

90% of Python programmers don't know these seven uses of underscore

Algo Insights
Coding Nexus
Published in
3 min readFeb 2, 2025

--

Underscores (_) in Python serve more purposes than most developers realize. While beginners often associate underscores with variable names, seasoned Python programmers leverage them for various practical applications. Here are seven powerful uses of underscores in Python that 90% of programmers might not know.

1. Retrieve the Last Computed Value

In an interactive Python shell (REPL), you can use an underscore (_) to retrieve the result of the last evaluated expression.

Example:

>>> 5 + 10
15
>>> _ * 2 # Uses the last computed value (15)
30

This is useful when performing quick calculations without storing intermediate results.

2. Placeholder for Loop Variables

You can use an underscore as a placeholder when you don't need to use the loop variable inside a loop. This makes it clear that the loop variable is intentionally unused.

Example:

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

Output:

Hello!
Hello!
Hello!

This technique is handy when executing a code block multiple times without considering the iteration index.

3. Digit Separator for Readability

Large numbers can be hard to read. Python allows you to use underscores to separate digits, improving readability without affecting the number's value.

Example:

# Underscores improve readability but do not affect the value
num = 1_000_000 # Same as 1000000
print(num)

Output:

1000000

This is particularly helpful when dealing with financial or scientific calculations.

4. Declaring Variables for Internal Use

A double underscore (__var) signals that a variable is meant for internal use. If you want stronger name-mangling to indicate it's private, you should use a double underscore (__internal_var), which triggers name mangling.

--

--

Coding Nexus
Coding Nexus

Published in Coding Nexus

Coding Nexus is a community of developers, tech enthusiasts, and aspiring coders. Whether you’re exploring the depths of Python, diving into data science, mastering web development, or staying updated on the latest trends in AI, Coding Nexus has something for you.

Algo Insights
Algo Insights

Written by Algo Insights

Algo Insights: Unlocking the Future of Trading with Code, Data, and Intelligence. https://linktr.ee/Algo_Insights

Responses (4)

Write a response