1

I am using python to learn about data science. Everything is fine but recently I found below code in a book. I can't understand for what purpose '_' is being used.

def raw_majority_vote(labels):
    votes = Counter(labels)
    winner, _ = votes.most_common(1)[0]
    return winner
Sajjan Kumar
  • 353
  • 1
  • 3
  • 16

3 Answers3

1

In this piece of code you posted, the _ is a variable name.

You can assign values to _.

I.e.:

>>> _ = "test"
>>> print _

Output:

test

If you take a look at Counter.most_common() docs, you'll see this message:

Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

So, in your code, winner, _ = votes.most_common(1)[0]

The variable winner gets the first value of the first tuple contained in this most_common list. And the variable, _, gets the second value of the first tuple in this list.

In this case:

winner = 'a'
_ = 5
dot.Py
  • 5,007
  • 5
  • 31
  • 52
1

It's a throwaway variable. Whatever votes.most_common(1)[0] is can be unpacked to two values and the writer of that script is only interested in the first value.

awesoon
  • 32,469
  • 11
  • 74
  • 99
SuperShoot
  • 9,880
  • 2
  • 38
  • 55
0

Usually it is used when you don't care about returned variable and you want to discard it but still prevent any ValueErrors.

mic4ael
  • 7,974
  • 3
  • 29
  • 42