Search code examples
pythondummy-variablewalrus-operator

Underscore variable with walrus operator in Python


In Python, the variable name _ (underscore) is often used for throwaway variables (variables that will never be used, hence do not need a proper name).

With the walrus operator, :=, I see the need for a variable that is rather short lived (used in say only one line of code). I wonder if the use of _ is reasonable to use also in this case, or if it might be confusing for someone reading the code?

Example:

a = (dummy := pd.Series([1, 2, 3, 4, 5]))[dummy > 2]

Here a pandas series is created and immediately filtered. The name dummy could in my opinion be replaced with _:

a = (_ := pd.Series([1, 2, 3, 4, 5]))[_ > 2]

Solution

  • You are using the variable dummy, to filter the series. Therefore, don't replace it with _.