what does 'for _ in range()' mean?

Erik Max Francis max at alcyone.com
Wed Jul 28 05:13:34 EDT 2004


Tor Iver Wilhelmsen wrote:
> 
> Roy Smith <roy at panix.com> writes:
> 
> > I've never heard of that convention before.  Is it some python-specific
> > thing, or is my ignorance more global in scope?
> 
> It may derive from Prolog, where you use _ as an unbound "wildcard".
> E.g. to declare that X is a parent if X is a father or mother:

It may, but to answer the original poster's question, it's not uncommon
to see this in other languages (where _ is a valid identifier).  _ often
means a variable one's not interested in the value of, but which is
needed for syntactic reasons.

Note that _(...) as a macro call has another conventional meaning, which
comes from gettext, where one uses _("string literal") to indicate a
string that needs localization.

Note also there's a noticeable difference between the anonymous variable
in Prolog and the use of _ in Python; in Prolog, the anonymous variable
can be used multiple times in the same expression and there is no need
for the variable to represent the same thing.  In

	middle(X) :- inOrder(_, X, _).

there's no need for _ to map to the same object -- middle(c) would be
true even if inOrder(b, c, d) were the only known relevant fact, and b
and d are certainly not equal.  That's not true in Python, where _ is
just another name with no special semantics.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Never be the first to believe / Never be the last to deceive
    -- Florence, _Chess_



More information about the Python-list mailing list