The Many Faces of the Underscore (`_`) in Python

Published:
Last updated:
By Jeferson Peter
Python

Common uses of underscore

  1. Ignore a value in unpacking
x, _, y = (1, 2, 3)
print(x, y)   # 1 3
  1. Throwaway variable in loops
for _ in range(3):
    print("Hello")

# Hello
# Hello
# Hello
  1. Last result in the REPL
>>> 5 + 5
10
>>> _
10
  1. Private variable convention
_class_var = "intended for internal use"
  1. Double underscore name mangling
class MyClass:
    def __secret(self):
        return "hidden"

obj = MyClass()
# print(obj.__secret())  # Error
print(obj._MyClass__secret())  # Access with mangled name

conclusion

The underscore is a versatile symbol in Python: it can mean "ignore this," "internal use," or even "access last value." Context tells you which one applies.