I am using the itertool library to go through a list named group
. Kindly explain what will the following statement do.
sum(1 for _ in group)
I am confused about the underscore and how it works.
I am using the itertool library to go through a list named group
. Kindly explain what will the following statement do.
sum(1 for _ in group)
I am confused about the underscore and how it works.
sum(1 for _ in group)
Here, the _
(underscore), by convention, indicates that the value is not important and is not being used anywhere, thus, it can be ignored. Here, you are more concerned with looping and not the loop variable.
So, in your case, since you are adding 1
for every element in group
the above code will basically return the number of elements in group
.
Please note that it is a convention to use _
as the loop variable if you aren't going to use it. You can access the loop variable _
if you want to. For example, consider the following code snippet.
for _ in range(5):
print(_)
Output:
0
1
2
3
4
But please avoid doing this.
loop when there is no need for a return I will give you an example
need return from loop
clients = ["M-Waseem Ansari","Emerson Pedroso","Some one"]
for client in clients:
print(f'Clients name is {client}')
When you dont need return
clients = ["M-Waseem Ansari","Emerson Pedroso","Some one"]
for _ in clients:
print('new Client')
the underscore None variable
It's a Pythonic convention to use underscore as a variable name when the returning value from a function, a generator or a tuple is meant to be discarded.
In your example, the code inside the for loop does not make any use of the values generated by range(0,int(input())), so using an underscore makes sense as it makes it obvious that the loop does not intend to make use of it.