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(input())):
print('underscore is', _)
stamps.add(raw_input().strip())
print(stamps)
Output:
>>>2
underscore is 0
>>>first
set(['first'])
underscore is 1
>>>second
set(['second', 'first'])
I put 2 as the first raw input. How does the function know that I'm only looping twice? This is throwing me off because it isn't the typical...for i in xrange(0,2) structure.
At first my thinking was the underscore repeats the last command in shell. So I added print statements in the code to see the value of underscore...but the values just show the 0 and 1, like the typical loop structure.
I read through this post already and I still can't understand which of those 3 usages of underscore is being used.
What is the purpose of the single underscore "_" variable in Python?
I'm just starting to learn Python so easy explanations would be much appreciated!
The underscore is like a normal variable in your program.
ncoghlan's answer lists 3 conventional uses for
_
in Python: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:where
_
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
where the value of the loop variable is used, it is the convention to use a variable name such as
i
,j
instead of_
.Your code
is exactly equivalent to this:
Because whatever you put in
range()
has to be calculated before the loop starts, so the firstint(raw_input())
is asked only once. If you use something likefor i in range(very_expensive_list)
it will take a bunch of time then start the loop.For anyone that is trying to understand how underscore and input works in a loop - after spending quite sometime debugging and printing - here's the code that made me understand what was going on.
User input:
Output:
Bonus - notice how there's an int() conversion for the first line in the for loop?
The first input is 2, so int() converts that just fine. You can tell the first line of code is being ignored now because putting the second input, 'Dog', through int() would yield an error. Can't words into integer numbers.