Getting to know the Underscore(_) Symbol in Python
The underscore symbol (_) in python holds remarkable functionalities that can enhance your coding experience and the understanding of the language. Here are some ways you can utilize the underscore symbol in your next project. (note: some of these exampls work only with python 3.10 and above)
- As a Temporary Container
The underscore symbol by default is an automatic variable that saves the value of the last executed expression in an interactive interpreter session.
For instance, consider the following:
>>> 25
25
>>> _
25
Even within scripts, the underscore variable proves its worth:
>>> a = 2
>>> b = 2
>>> ab = a * b
>>> absquare = _ ** 2
>>> print(absquare)
since the last executed expression is a*b, _ holds the value of 4.(You might see an error if you are trying this code in an old file, as the last excuted expression would be what you executed before this code.)
2. As an “Else” operation.
When using the match-case syntax, _ can be use an Else clause and can also help to reduce unexpected errors in your codebase.
>>>def some(caset):
>>> match caset:
>>> case 1:
>>> return "You entered 1"
>>> case 2:
>>> return "You entered 2"
>>> case 3:
>>> return "You entered 3"
>>> case 4:
>>> return "You entered 4"
>>> case 5:
>>> return "This is the final number, number 5"
>>> case _:
>>> return "\"Something\" is wrong somewhere"
>>>some(1)
'You entered 1'
>>>some('b')
'"Something" is wrong somewhere'
Any input above that doesn’t match the cases listed(no pun intended) will result to the execution of the case _.
3. To Ignore a Particular Object or Value
The _ variable is most times referred to as the Throw away variable. It’s mostly used to ignore or “Throw away” a particular object or value.
for instance, when unpacking:
>>>x, _, y = (1, 2, 5)
>>> x
1
>>> y
5
4. Extending numbers
The _ symbol is used to concatenate numbers for more readability, for instance, Typing a large number like 1 billion can strain readability but using _ makes it more comprehensive. e.g.
>>> billion = 1_000_000_000
>>> billion
1000000000
Conclusion
From efficiently storing previous expressions to serving as an “else” sentinel in match-case syntax, the _ variable is a seamlessly versatile and functional symbol in python improving readability and streamlining operations in our codebase.
References
1. Stack Overflow — What is the purpose of the single underscore variable in Python?
2. Python 3.11 Documentation — Lexical Analysis — Reserved Classes of Identifiers