English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Underscore (_) in Python

In Python, in some cases we use Single Underscore (_), and in some cases we use Double Underscores (__).

In Python, there are the following cases where we use underscores.

  • If we want to store the value of the last expression in the interpreter.

  • If we want to ignore some values.

  • Used to declare variables or functions.

  • The number used to separate the horizontal values of numbers.

  • It is also used as “Internationalization (i18n)”or “Localization (l10n)”function.

Now, provide some examples in each case.

Used for translators

The Python interpreter stores the value of the last expression in "_".

>>> 20 
20 
>>> _ 
20 
>>> _ + 3 
23

Ignore values

Underscore is also used to ignore values.

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

here x = 1, y = 3and ignore the value2.

Used to declare variables and functions

Python does not support private, so we cannot force something to be private, but we can directly call it from other modules.

single_trailing_underscore_

Easily using this conversion can avoid conflicts with Python keywords and built-in keywords.

__double_leading_underscore

This is mangle, used to avoid name conflicts between properties.

If you write the method name "__display" in the class, the name will be modified as "_ClassName__display".

__double_leading_and_trailing_underscore__

In some cases, we use this conversion. Like _init_.

The number used to separate the horizontal values of numbers

dec_base = 1_000_000
print(dec_base)  # 1000000

Internationalization (i18n)/Localization (l10n) of i

This is just a convention, the underscore here is just to indicate the function18n / l10bind to an underscore variable, not from the C convention.