0

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.

Bilesh Ganguly
  • 3,000
  • 2
  • 31
  • 50
  • 2
    It's a variable name like any other. Usually people use `_` for any "silent" variable that won't be relevant elsewhere. – Julien May 10 '21 at 04:35
  • 1
    Your example just returns the number of elements in `group` by summing across a fixed value, `1` for each element, no matter what that element is. The most common place to see this "don't care" pick from an iterator is when you want to have a loop with a fixed number of repeats, so you use code like `for _ in range(5):` – Joffan May 10 '21 at 04:40

2 Answers2

2

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.

Bilesh Ganguly
  • 3,000
  • 2
  • 31
  • 50
0

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.