Underscore _ as variable name in Python [duplicate] Underscore _ as variable name in Python [duplicate] python python

Underscore _ as variable name in Python [duplicate]


Yep, _ is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:

_,s = min( (len( values[s]), s)             for s in squares             if len(values[s]) > 1        )

you might code

s = min((s for s in squares if len(values[s])>1),         key=lambda s: len(values[s]))

(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key= optional parameter is generally the best way to do DSU;-).


Your interpretation is correct. Outside of the special meaning in interactive mode _ is just used as a "don't care" variable name, especially in unpacking.


You are correct. In non-interactive mode _ has no special meaning. Indeed, Norvig just wants to convey that he doesn't care about the value of that variable.

Offtopic: That article by Norvig is very nice. A recommended read.