Underscore (_
) has so many usages in Python.
Today, I want to walk you through 7 of them, which I find pretty useful from time to time.
Let’s begin!
#1) Retrieve the last computed value
One of the most elegant utilities of underscore is to retrieve the last computed value, as demonstrated below:
This works both in a script (.py
) and an interactive environment like Jupyter Notebook.
#2) Placeholder for loop variable
Instead of explicitly declaring a loop variable, one can also run loops as follows:
#3) Digit separator
When declaring large numbers, it can be difficult to interpret them. Underscore simplifies this:
#4-7) Declaring names
We can also use underscore while naming objects.
A single leading underscore is used to declare variables for internal use. Thus, they cannot be imported during wild imports (
from file import *
)
A single trailing underscore is used to avoid conflict with reserved keywords, as depicted below:
Double leading underscores are used to invoke name mangling. This way, one can prevent direct access to private variables outside a class:
We covered this in detail in this issue: Python Does Not Fully Deliver OOP Encapsulation Functionalities.
Finally, double leading and trailing underscores, as you may already know, are used to define magic methods:
This is a guide on the 20 most common magic methods in Python:
Read this issue for more details: A Consolidated List of 20 Most Common Magic Methods.
Done!
These were the 7 elegant ways to use the underscore keyword in Python.
👉 Over to you: What other usages have I missed?
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights.
The button is located towards the bottom of this email.
Thanks for reading!
Whenever you are ready, here’s one more way I can help you:
Every week, I publish 1-2 in-depth deep dives (typically 20+ mins long). Here are some of the latest ones that you will surely like:
[FREE] A Beginner-friendly and Comprehensive Deep Dive on Vector Databases.
You Are Probably Building Inconsistent Classification Models Without Even Realizing
Why Sklearn’s Logistic Regression Has no Learning Rate Hyperparameter?
PyTorch Models Are Not Deployment-Friendly! Supercharge Them With TorchScript.
DBSCAN++: The Faster and Scalable Alternative to DBSCAN Clustering.
Federated Learning: A Critical Step Towards Privacy-Preserving Machine Learning.
You Cannot Build Large Data Projects Until You Learn Data Version Control!
To receive all full articles and support the Daily Dose of Data Science, consider subscribing:
👉 If you love reading this newsletter, feel free to share it with friends!
Underscore for formatting number literals are so nice. Too bad it’s not that used in practice.