One more tip - if anyone is learning Python on HackerRank, knowing this is critical for starting out.
I'm trying to understand this code:
stamps = set()
for _ in range(int(raw_input())):
print 'underscore is', _
underscore is 0
underscore is 1
ncoghlan's answer lists 3 conventional uses for
_ in Python:
- To hold the result of the last executed statement in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
For translation lookup in i18n (imported from the corresponding C conventions, I believe), as in code like:
raise forms.ValidationError(_("Please enter a correct username"))`
As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored, as in code like:
label, has_label, _ = text.partition(':')
Your question is which one of these is being used in the example in your code. The answer would be that is a throwaway variable (case 3), but its contents are printed here for debugging purposes.
It is however not a general Python convention to use
_ as a loop variable if its value is used in any way. Thus you regularly might see:
for _ in range(10): print("Hello world")
_ immediately signals the reader that the value is not important and it the loop is just repeated 10 times.
However in a code such as
for i in range(10): do_something(i)
where the value of the loop variable is used, it is the convention to use a variable name such as
j instead of