Underscore (_) in Python

The underscore (_) in Python has multiple uses, and its meaning depends on the context in which it appears. Below is a detailed explanation of all its different uses.

1. Ignoring Values (Throwaway Variable)

A single underscore is commonly used when we want to ignore a specific value while unpacking a collection.

Example 1: Ignoring a value while unpacking a tuple

x, _, y = (1, 2, 3)

print(x)  # Output: 1
print(y)  # Output: 3

Here, _ is used as a throwaway variable to ignore the value 2.

Example 2: Ignoring the loop variable

for _ in range(3):
    print("Hello")

Output:

Hello
Hello
Hello

Since the loop index is not needed, _ is used as a placeholder.

2. Underscore (_) in Python Interactive Shell

In the Python interactive shell (REPL), _ stores the result of the last executed expression.

Example (Run this in a Python shell like IDLE, Jupyter, or Terminal)

>>> 10 + 5
15
>>> _
15
>>> _ * 2
30

Output:

>>> 10 + 5
15
>>> _
15
>>> _ * 2
30

The underscore holds the value of the last evaluated expression (15) and is used again in the calculation.

3. Using _ as a Variable Name

A single underscore can be used as a regular variable name, although this is not common.

Example:

_ = "temporary value"
print(_)  # Output: temporary value

Here, _ is used as a normal variable.

4. Single Leading Underscore (_var): Weak “Internal Use” Indicator

A single leading underscore is a convention (not enforced by Python) that indicates a variable is for internal use.

Example:

class Person:
    def __init__(self, name):
        self._name = name  # _name is meant to be "internal"

p = Person("Alice")
print(p._name)  # Output: Alice (Can still be accessed)

Output:

Alice

_name is not truly private, but it signals that this variable should not be accessed directly.

5. Double Leading Underscore (__var): Name Mangling

A double underscore before a variable triggers name mangling, preventing accidental access.

Example:

class Test:
    def __init__(self):
        self.__private = "Secret"

obj = Test()
# print(obj.__private)  # Uncommenting this will cause an AttributeError
print(obj._Test__private)  # Output: Secret

Output:

Secret

The variable __private is internally renamed to _Test__private, making it harder to access.

6. Double Leading and Trailing Underscore (__var__): Dunder (Magic) Methods

Python uses double underscores around certain names for special (dunder) methods like __init__, __str__, etc.

Example:

class Sample:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Sample({self.name})"

obj = Sample("Example")
print(obj)  # Calls obj.__str__()

Output:

Sample(Example)

Names like __init__ and __str__ are part of Python’s built-in behavior.

7. Trailing Underscore (var_): Avoiding Conflicts with Keywords

A trailing underscore is used when a variable name conflicts with a Python keyword.

Example:

class_ = "Python Class"  # 'class' is a keyword, so we use 'class_'
print(class_)  # Output: Python Class

Output:

Python Class

class_ is used instead of class, which is a reserved keyword.

8. Underscore in Numeric Literals for Readability

Python allows underscores in numbers to make them more readable.

Example:

num = 1_000_000  # Easier to read as 1,000,000
print(num)  # Output: 1000000

Output:

1000000

The underscores (_) are ignored when interpreting the number.

Summary of Underscore Usage in Python

Underscore SyntaxMeaning
_Throwaway variable or stores last result in REPL
_varConvention for internal use (not enforced)
__varName mangling (makes access difficult)
__var__Special (dunder) methods in Python
var_Used when the variable name conflicts with a keyword
1_000_000Improves readability of numbers

Final Thoughts

  • The underscore is an important and very flexible character in Python.
  • It is used for ignoring values, indicating internal use, preventing name conflicts, and improving readability.
  • Name mangling with __var is useful in avoiding accidental access to class variables.