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

J

Jon Perez

I saw this code snippet:

sock.listen(20)
for _ in range(20):
newsock, client_addr = sock.accept()
print "Client connected:", client_addr
data[newsock] = ""

why use _ for this example? Is there any
optimization to be had using it?

I know that in the interpreter _ means the
last value calculated, but what does _ mean
inside source code?
 
D

David Eppstein

Jon Perez said:
I saw this code snippet:

sock.listen(20)
for _ in range(20):
newsock, client_addr = sock.accept()
print "Client connected:", client_addr
data[newsock] = ""

why use _ for this example? Is there any
optimization to be had using it?

I know that in the interpreter _ means the
last value calculated, but what does _ mean
inside source code?

AFAIK it's just a variable like any other, but by convention it means
that you don't intend to use that value, just read it and ignore it.
 
R

Roy Smith

David Eppstein said:
Jon Perez said:
I saw this code snippet:

sock.listen(20)
for _ in range(20):
newsock, client_addr = sock.accept()
print "Client connected:", client_addr
data[newsock] = ""

why use _ for this example? Is there any
optimization to be had using it?

I know that in the interpreter _ means the
last value calculated, but what does _ mean
inside source code?

AFAIK it's just a variable like any other, but by convention it means
that you don't intend to use that value, just read it and ignore it.

I've never heard of that convention before. Is it some python-specific
thing, or is my ignorance more global in scope?

In any case, I'd vote for some more useful variable name. In the above
case, something like connectionNumber or whatever would be more
self-explanitory.
 
T

Tor Iver Wilhelmsen

Roy Smith said:
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:

parent(X) :- fatherOf(X, _), !.
parent(X) :- motherOf(X, _), !.

because you don't need to know anything about the child, just that it
exists. If you used a variable like Y, you would either also need to
say something about Y, or Y would end up in the resolved answer.

(The ! is a "cut", and means we're not interested in more than one
answer.)
 
E

Erik Max Francis

Tor said:
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.
 
M

Matteo Dell'Amico

Roy said:
I've never heard of that convention before. Is it some python-specific
thing, or is my ignorance more global in scope?

I have seen it in logic and functional programming, where '_' -
differently from python - has a special meaning: assignments to '_' are
discarded in functional programming and

I guess that it's value in the interpreter, instead, comes from perl's $_.
In any case, I'd vote for some more useful variable name. In the above
case, something like connectionNumber or whatever would be more
self-explanitory.

In that case, I interpret is as this: that loop has to be iterated 20
times, and the looping variable is uninfluent. In this cases, again by
convention, in C programs the variable is often called "i".
 
M

Matteo Dell'Amico

Whoops, part missing :)
I have seen it in logic and functional programming, where '_' -
differently from python - has a special meaning: assignments to '_' are
discarded in functional programming and

in logic programming it is seen as a jolly "match-all" value.
 
J

John Roth

David Eppstein said:
Jon Perez said:
I saw this code snippet:

sock.listen(20)
for _ in range(20):
newsock, client_addr = sock.accept()
print "Client connected:", client_addr
data[newsock] = ""

why use _ for this example? Is there any
optimization to be had using it?

I know that in the interpreter _ means the
last value calculated, but what does _ mean
inside source code?

AFAIK it's just a variable like any other, but by convention it means
that you don't intend to use that value, just read it and ignore it.

What convention? I have to agree with a couple
of other posters; I've never heard of it before.

If it really is a convention, it would be nice to have it
documented somewhere (like the single underscore
in front of a variable means "weak internal use").
Somewhere is most likely PEP 8 - the Python
Style Guide.

John Roth
 
E

Erik Max Francis

John said:
What convention? I have to agree with a couple
of other posters; I've never heard of it before.

If it really is a convention, it would be nice to have it
documented somewhere (like the single underscore
in front of a variable means "weak internal use").
Somewhere is most likely PEP 8 - the Python
Style Guide.

A convention doesn't need to have official sanction to be a convention.
 
P

Peter Hansen

John said:
What convention? I have to agree with a couple
of other posters; I've never heard of it before.

I would imagine it's the same convention that suggests that
the value assigned to _ is ignored in the following type
of code, which surely most of us have seen around here a
few times:

a, b, _ = tupleWithThreeItems

-Peter
 
M

Michael Charlton

I must admit I've never heard of this before either but, I'm no world
authority on Python.

I've just tried it on some toy code and as always I run pychecker on it. So
with

def spam():
for i in range(10):
print 'a'

I get "Local variable (i) not used". But with the following:

def spam():
for _ in range(10):
print 'a'

I get no such warning. Is pychecker aware of this convention or is it
coincidental? I don't
know.

Michael Charlton



David Eppstein said:
Jon Perez said:
I saw this code snippet:

sock.listen(20)
for _ in range(20):
newsock, client_addr = sock.accept()
print "Client connected:", client_addr
data[newsock] = ""

why use _ for this example? Is there any
optimization to be had using it?

I know that in the interpreter _ means the
last value calculated, but what does _ mean
inside source code?

AFAIK it's just a variable like any other, but by convention it means
that you don't intend to use that value, just read it and ignore it.
 
P

Peter Otten

Michael said:
I've just tried it on some toy code and as always I run pychecker on it.
So with

def spam():
for i in range(10):
print 'a'

I get "Local variable (i) not used". But with the following:

def spam():
for _ in range(10):
print 'a'

I get no such warning. Is pychecker aware of this convention or is it
coincidental? I don't

Found in Config.py:

_DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]

Peter
 
S

Skip Montanaro

Peter> Found in Config.py:

Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]

One might consider adding 'i' to that list. If nothing else, it would avoid
a bunch of warnings... ;-)

Skip
 
C

Christopher T King

Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]

One might consider adding 'i' to that list. If nothing else, it would avoid
a bunch of warnings... ;-)

But then we'd have to add a, t, n, and x, too ;)
 
P

Peter Otten

Skip said:
Peter> Found in Config.py:

Peter> _DEFAULT_UNUSED_LIST = [ '_', 'empty', 'unused', 'dummy', ]

One might consider adding 'i' to that list. If nothing else, it would
avoid
a bunch of warnings... ;-)

All but "_" work as prefix, too, so that could avoid a bit too much...

Peter
 
T

Terry Reedy

What convention? I have to agree with a couple
of other posters; I've never heard of it before.

Coming from Fortran and C, I myself use i for 'don't care' looping vars.
If it really is a convention,

It is obviously not a universal convention. What does library code use?
it would be nice to have it
documented somewhere (like the single underscore
in front of a variable means "weak internal use").
Somewhere is most likely PEP 8 - the Python
Style Guide.

In the interactive interpreter, _ is bound to the last expression evaluated
that is otherwise unassigned.
Traceback (most recent call last):
3

This is the only official use of _ that I know of and it is documented
somewhere.

Terry J. Reedy
 
P

Phil Frost

At Some Point, Someone Asked Something to The Effect of:
where does this _ thing come from?

In ML, _ is used as magic "don't care" variable. It's often used when
unpacking tuples and some elements are irrelevant. Example:

Ocaml:
let (fu, bar, _, _) = returns_a_4_tuple ()

Python:
(fu, bar, _, __) = returns_a_4_tuple()

One difference is that _ is allowed multiple times in Ocaml, while in
Python it is not. Also to Python, it's a variable like any other, while
in Ocaml it's magic.
 
P

Peter Hansen

Phil said:
Python:
(fu, bar, _, __) = returns_a_4_tuple()

One difference is that _ is allowed multiple times in Ocaml, while in
Python it is not.

Why do you say that?

c:\>python
Python 2.3.4 (#53, May 25 2004, 21:17:02) ....4

Looks to me like Python doesn't care how many times it rebinds
a name while unpacking a tuple.

-Peter
 
D

David Eppstein

Peter Hansen said:
Why do you say that?

c:\>python
Python 2.3.4 (#53, May 25 2004, 21:17:02) ....
4

In that context, it's allowed multiple times, but in some other contexts
it's not:
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top