Python underscore as a function parameter Python underscore as a function parameter python python

Python underscore as a function parameter


In Python shells, the underscore (_) means the result of the last evaluated expression in the shell:

>>> 2+35>>> _5

There's also _2, _3 and so on in IPython but not in the original Python interpreter. It has no special meaning in Python source code as far as I know, so I guess it is defined somewhere in your code if it runs without errors.


From what I've been able to figure out, it seems like this is the case:

_ is used to indicate that the input variable is a throwaway variable/parameter and thus might be required or expected, but will not be used in the code following it.

For example:

# Ignore a value of specific location/index for _ in range(10)     print("Test")  # Ignore a value when unpacking a,b,_,_ = my_method(var1) 

(Credit to this post)

The specific example I came across was this:

    def f(_):        x = random() * 2 - 1        y = random() * 2 - 1        return 1 if x ** 2 + y ** 2 < 1 else 0


underscore is considered a 'don't care' variable, furthermore IDEs like PyCharm will not give a warning for it if it is unused

so in a function

def q(a, b, _, c):    pass

the IDE will underline a,b and c (unused parameter) but not the underscore

why would you use it and not omit the parameter?

->when you inherit from some class and want to override a function where you don't want to use some parameter

other common use is to indicate you don't want to use a part of a tuple when you iterate (or other unpacking) - this reduces clutter

names_and_food = [('michael', 'fruit'), ('eva', 'vegetables')]for name, _ in names_and_food:    print(name)

I cant find it in any python PEP, but pylint has it even in the FAQ