0 votes
1 view
in Python by (47.8k points)

What is the meaning of _ after for in this code?

if tbh.bag:

n = 0 

for _ in tbh.bag.atom_set():

n += 1

1 Answer

0 votes
by (107k points)

In Python _ has 3 main conventional uses:

  1. The first one is it holds the result of the last executed expressions or statements in an interactive interpreter session. This pattern was set by the standard CPython interpreter, and other interpreters have followed suit.

  2. It is also used for translation lookup in i18n(internationalization), the code looks like as follows: 

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

  1. The third and most important use of _ is, it is a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:-

label, has_label, _ = text.partition(':')

The last two purposes can conflict, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 20, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...