Unlock Python’s Secret: Master the Underscore (_) for Cleaner Code
This guide explores the versatile underscore '_' in Python, showing how to discard unwanted variables, simplify loops, improve numeric readability, leverage REPL shortcuts, and why using it as a regular variable is discouraged.
The underscore '_' is a gem in Python, offering many handy uses that often go unnoticed; this article explains the various ways to employ a single underscore in Python code and the scenarios where it shines.
1. Discarding Variables
When a variable is unnecessary, instead of creating a named placeholder like temp or temporary_variable , you can use '_' to indicate the value should be ignored.
<code>first_name, middle_name, last_name = ["fname", "mname", "lname"]
print(first_name, last_name)
</code>Since middle_name is not needed, replace it with '_' to mark it as a discarded variable:
<code>first_name, _, last_name = ["fname", "mname", "lname"]
print(first_name, last_name)
</code>This does not affect interpreter behavior; it simply signals to developers that the variable is irrelevant.
2. Unused Loop Variables
In loops where the iterator value is not required, you can replace the loop variable with '_' to clarify its irrelevance.
<code>for x in range(10):
num = num * 10
</code>Here, x is unused. Using '_' makes the intent clear:
<code>for _ in range(10):
num = num * 10
</code>You can also apply this pattern with enumerate when you only need the index:
<code>word_list = ["word-1", "word-2", "word-3", "word-4"]
for idx, _ in enumerate(word_list):
print(idx)
</code>3. Making Large Numbers More Readable
Python allows underscores inside numeric literals to improve readability, similar to digit grouping in formatted numbers.
<code>num_1 = 134578920
num_2 = 134_578_920
print(num_1)
print(num_2)
</code>Using f-strings, you can format the output with commas or underscores:
<code>print(f"{num_1:,}")
print(f"{num_1:_}")
</code>4. REPL Tricks
In an interactive REPL session, '_' automatically stores the result of the last expression, allowing quick reuse without defining a new variable.
<code>>> 2 + 3
5
>>> _
5
</code>This shortcut speeds up exploratory coding.
5. Legal Variable Name
Technically, '_' is a valid identifier and can be used as a regular variable name, but it is strongly discouraged unless you intend to prank others.
<code>_ = "Never Gonna Give You Up"
print(_)
</code>Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
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.