Unlocking Python’s Underscore: 4 Powerful Uses You Should Know
This article explains four practical ways the underscore (_) is used in Python—retrieving the last expression result, discarding unwanted values, marking private module members, and improving readability of large numeric literals—with clear code examples.
1. Represent the value of the last expression
In Python the underscore (_) holds the result of the most recent expression that was not assigned to a variable, similar to the $? variable in a Linux shell.
>> 3+5
8
>>> _
8
>>> _*3
24
>>> _
24Note that the underscore only captures results of expressions without an explicit variable; if a variable receives the result, the underscore still reflects the previous value.
>> x = 3+8
>>> _
242. Discard unwanted values
The underscore can act as a “black hole” to ignore values you do not need.
x, _, y = (1, 2, 3)Only x and y are kept.
for _ in range(100):
...In a for loop the underscore indicates that the loop variable is unused.
3. Indicate private functions and variables
When writing modules, a leading underscore marks names that should not be exported with from module import *. Double underscores trigger name‑mangling.
_var1 = 100
var2 = 200
def func1():
print(_var1)
print(var2)
def __func2():
print(_var1)
print(_var2) >> from moda import *
>>> var2
200
>>> _var1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_var1' is not defined
>>> func1()
100
200
>>> __func2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__func2' is not defined4. Separate large numeric literals
Since Python 3.6 you can use underscores inside numeric literals to improve readability, similar to commas in other languages. They work for decimal, binary, octal, and hexadecimal literals.
a = 1_000_000
print(a) # 1000000
b = 0b_111_1110
print(b) # 126
print(bin(b)) # 0b1111110
o = 0o12_34
print(o) # 668
print(oct(o)) # 0o1234
h = 0x_0a_ef
print(h) # 2799
print(hex(h)) # 0xaefThese underscore usages make large numbers easier to read.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
