- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Underscore(_) in Python
In Python in some cases we use Single Underscore(_) and some cases we use Double Underscores (__).
In Python has following cases, where we use underscore.
- If we want to store the value of last expression in interpreter.
- If we want to ignore some values.
- For declaration of variable or function.
- To separate digits of number lateral value.
- It is also used as ‘Internationalization (i18n)’ or ‘Localization (l10n)’ functions.
Now some examples on every cases.
Used in interpreter
The Python Interpreter stores the last expression value in the '_'.
>>> 20 20 >>> _ 20 >>> _ + 3 23
Ignoring the values
Underscore is also used for ignoring the values.
x, _, y = (1, 2, 3)
Here x = 1, y = 3 and ignore the value 2.
Used for declaring variable and function
Python does not support private, so we cannot force something’s private ones but we can call it directly from other modules.
Using this conversion easily can avoid conflicting of Python keywords and built-ins.
This is mangle, it is used to avoid conflicts of attributes name between names.
If you write a method name “__display” in a class, the name will be mangled in “_ClassName__display” form.
In some cases we use this conversion. Just like _init_.
To separate digits of number lateral value
dec_base = 1_000_000 print(dec_base) # 1000000
As Internationalization (i18n)/Localization (l10n) functions
This is just a convention not any syntactic functions here underscore just bind the i18n/l10n to underscore variable has been from C convention.
Kickstart Your Career
Get certified by completing the courseGet Started