Avi Chawla
Avi Chawla

@_avichawla

10 Tweets 18 reads Feb 08, 2025
90% of Python programmers don't know these 7 uses of underscore:
1) Retrieve the last computed value
You can retrieve the last computed value using underscore, as demonstrated below: x.com
2) Placeholder for loop variable
Instead of explicitly declaring a loop variable, you can also use it as a placeholder for a loop variable: x.com
3) Digit separator
When declaring large numbers, it can be difficult to interpret them. Underscore simplifies this: x.com
4) Declare variables for internal use
A single leading underscore is used to declare variables for internal use.
These are not imported during wild imports (from file import *): x.com
5) Avoid conflict with keywords
A single trailing underscore is used to avoid conflict with reserved keywords, as depicted below: x.com
6) Indicate private attributes
Double leading underscores prevent direct access (using obj [.] attribute_name) and communicate that the attribute is private.
However, these attributes can still be accessed outside the class as shown below: x.com
7) Magic methods
Finally, double leading and trailing underscores are used to define magic methods: x.com
Here is a cheat sheet of the 20 most common magic methods in Python: x.com
That's a wrap!
If you enjoyed this tutorial:
Find me → @_avichawla
Every day, I share tutorials and insights on DS, ML, LLMs, and RAGs.

Loading suggestions...