python – What is the purpose of a single underscore "_" variable?

Question:

What does _ mean after for in this code?

if tbh.bag:
   n = 0
   for _ in tbh.bag.atom_set():
      n += 1

translation of the question What is the purpose of the single underscore "_" variable in Python? from @alwbtc

Answer:

_ has 5 main standard uses in Python:

  1. To store the result of the last executed expression in the interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit.

  2. As a generic variable name indicating that part of the result of a function is intentionally ignored (conceptually, it is discarded.). As in type code:

     label, has_label, _ = text.partition(':')
  3. As part of a function definition (using either def or lambda ) where the signature is fixed (e.g. by a callback or an API parent class), but this particular function implementation doesn't need all the parameters as in code, e.g.:

     callback = lambda _: True
  4. The python linter recognizes underscore as an intentionally unused variable (both uses above). for instance

     year, month, day = date()

    will trigger a lint warning if the day variable is not used later in the code, if day is really not needed, then you can fix it like this:

     year, month, _ = date()

    Same with lambda functions

     lambda arg: 1.0

    creates a function that requires one argument but does not use it, which will be caught by lint, this can be fixed by writing

     lambda _: 1.0

    An unused variable often hides an error/typo (created day , but next line uses dya )

  5. To search for a translation in i18n (see for example the gettext documentation), as in a similar code

     raise forms.ValidationError(_("Please enter a correct username"))

    The use of underscores for translation comes from documentation examples that have been copied/pasted for decades, for example:

     import gettext gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # ... print(_('Это переводимая строка.'))

translation of answer from @ncoghlan

Scroll to Top