Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k 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 (106k 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.6k points)
0 votes
2 answers
asked Jul 13, 2019 in Python by Sammy (47.6k points)

Browse Categories

...