469,312 Members | 2,496 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,312 developers. It's quick & easy.

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

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?
Jul 18 '05 #1
37 37347
In article <2m************@uni-berlin.de>,
Jon Perez <jb********@wahoo.com> wrote:
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.

--
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
Jul 18 '05 #2
In article <ep****************************@news.service.uci.e du>,
David Eppstein <ep******@ics.uci.edu> wrote:
In article <2m************@uni-berlin.de>,
Jon Perez <jb********@wahoo.com> wrote:
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.
Jul 18 '05 #3
Roy Smith <ro*@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:

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.)
Jul 18 '05 #4
Tor Iver Wilhelmsen wrote:

Roy Smith <ro*@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 && ma*@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_
Jul 18 '05 #5
Roy Smith wrote:
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".

--
Ciao,
Matteo
Jul 18 '05 #6
Whoops, part missing :-)

Matteo Dell'Amico wrote:
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.

--
Ciao,
Matteo
Jul 18 '05 #7
"David Eppstein" <ep******@ics.uci.edu> wrote in message
news:ep****************************@news.service.u ci.edu...
In article <2m************@uni-berlin.de>,
Jon Perez <jb********@wahoo.com> wrote:
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

--
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/

Jul 18 '05 #8
John Roth wrote:
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.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ But you're not going to be there tomorrow. And it's all about
tomorrow. -- Montgomery Brogan
Jul 18 '05 #9
John Roth wrote:
"David Eppstein" <ep******@ics.uci.edu> wrote:
Jon Perez <jb********@wahoo.com> wrote:
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.


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
Jul 18 '05 #10
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" <ep******@ics.uci.edu> wrote in message
news:ep****************************@news.service.u ci.edu...
In article <2m************@uni-berlin.de>,
Jon Perez <jb********@wahoo.com> wrote:
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.

--
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/

Jul 18 '05 #11
Michael Charlton wrote:
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

Jul 18 '05 #12
Is pychecker aware of this convention ...


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
Jul 18 '05 #13
On Wed, 28 Jul 2004, Skip Montanaro wrote:
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 ;)

Jul 18 '05 #14
Skip Montanaro wrote:
>> Is pychecker aware of this convention ...


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
Jul 18 '05 #15
> 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.
a=3
_ Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name '_' is not defined 3 3 _

3

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

Terry J. Reedy

Jul 18 '05 #16
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.
Jul 18 '05 #17
Phil Frost wrote:
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) ....
a = 1, 2, 3, 4
b, c, d, e = a
b, c, d, d = a
b, c, _, _ = a
_, _, _, _ = a
_

4

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

-Peter
Jul 18 '05 #18
Christopher T King wrote:
On Wed, 28 Jul 2004, Skip Montanaro wrote:
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 ;)


Don't forget j.
Jul 18 '05 #19
In article <Fa********************@powergate.ca>,
Peter Hansen <pe***@engcorp.com> wrote:
Phil Frost wrote:
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) ....
>>> a = 1, 2, 3, 4
>>> b, c, d, e = a
>>> b, c, d, d = a
>>> b, c, _, _ = a
>>> _, _, _, _ = a
>>> _ 4


In that context, it's allowed multiple times, but in some other contexts
it's not:
def foo(_,_): pass ....
File "<stdin>", line 1
SyntaxError: duplicate argument '_' in function definition


--
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
Jul 18 '05 #20
David Eppstein wrote:
In that context, it's allowed multiple times, but in some other contexts
it's not:
def foo(_,_): pass


...
File "<stdin>", line 1
SyntaxError: duplicate argument '_' in function definition


Uh, okay... and does Ocaml allow duplicating argument
names in whatever it has that passes for a function
definition? This is all a reach from the original
point of the thread, which was to use it as a throw-away
control variable in a for loop...

-Peter
Jul 18 '05 #21
David Eppstein wrote:
def foo(_,_): pass


The best solution then would probably be:

def foo(*_):
pass
Jul 18 '05 #22
Peter Hansen wrote:
Uh, okay... and does Ocaml allow duplicating argument
names in whatever it has that passes for a function
definition? This is all a reach from the original
point of the thread, which was to use it as a throw-away
control variable in a for loop...


It allows pattern-matching. You can say, for instance, something as:

foo(a, a) = True
foo(_, _) = False

This means that foo is true when its arguments are equal. Note, too,
that 'a' has a different value from '_'.

--
Ciao,
Matteo
Jul 18 '05 #23
Christopher T King <sq******@WPI.EDU> wrote in message news:<Pi**************************************@ccc 3.wpi.edu>...
On Wed, 28 Jul 2004, Skip Montanaro wrote:
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 ;)


In other languages, I've used "fcrt" as a dummy variable name, to
indicate that is only named because the Friendly Compiler Requires
This.
Jul 18 '05 #24
Matteo Dell'Amico wrote:
Peter Hansen wrote:
Uh, okay... and does Ocaml allow duplicating argument
names in whatever it has that passes for a function
definition? This is all a reach from the original
point of the thread, which was to use it as a throw-away
control variable in a for loop...


It allows pattern-matching. You can say, for instance, something as:

foo(a, a) = True
foo(_, _) = False

This means that foo is true when its arguments are equal. Note, too,
that 'a' has a different value from '_'.


I have no idea what you are talking about; sorry. The "code"
you show is not valid, and since you aren't talking about a
function *definition* (where duplicate names are disallowed)
but apparently about calling a function, I can't see that this
has the slightest thing to do with the topic at hand.

Therefore I'm sure I misunderstood what you meant... please
explain.

-Peter
Jul 18 '05 #25
Peter Hansen wrote:
I have no idea what you are talking about; sorry. The "code"
you show is not valid, and since you aren't talking about a
function *definition* (where duplicate names are disallowed)
but apparently about calling a function, I can't see that this
has the slightest thing to do with the topic at hand.


Of course this is not valid python code. :-)
This is a pseudo-functional language function definition. It is
specified by pattern matching:

foo(a, a) = True

means that calling foo with a tuple of two identical arguments returns
True, while

foo(_, _) = False

means that calling foo with a tuple of any two arguments returns False,
if the above condition isn't met.

The goal was to put into evidence the use of pattern-matching and '_'.
That's all. :-)

I hope this is clearer now...

--
Ciao,
Matteo
Jul 18 '05 #26
Matteo Dell'Amico wrote:
Peter Hansen wrote:
I have no idea what you are talking about; sorry.

[...snip attempted explanation...]
I hope this is clearer now...


Actually, not in the least, but I'm happy to go on faith that
you have a point and hope you have managed to communicate it
to others. :-|

-Peter
Jul 18 '05 #27
Peter Hansen wrote:
Actually, not in the least, but I'm happy to go on faith that
you have a point and hope you have managed to communicate it
to others. :-|


Let's try it again: in functional programming languages, you can use
pattern-matching, so that you can define functions in a declarative
fashion this way:

f(1) = 2
f(2) = 3
f(3) = 4
f(_) = 42

In python, this could be written as:

def f(x):
if x == 1:
return 2
elif x == 2:
return 3
elif x == 3:
return 4
else:
return 42

'_' is the identifier that means "anything here".

--
Ciao,
Matteo
Jul 18 '05 #28
Matteo Dell'Amico wrote:
Peter Hansen wrote:
Actually, not in the least, but I'm happy to go on faith that
you have a point and hope you have managed to communicate it
to others. :-|


Let's try it again: in functional programming languages, you can use
pattern-matching, so that you can define functions in a declarative
fashion this way:


Oh! Enlightment dawns.... we were still talking about Ocaml then.
I see.

So to get this back to the point that was being made:

Phil said Ocaml allowed multiple _ in tuple assignments but
that Python did not, while I attempted to correct that assertion by
showing that it in fact did.

David and you were discussing a case involving function languages,
which Python is not, where the use of multiple _ (which now has
syntactical meaning, as opposed to being just an "ignore this" by
convention) is allowed.

Sounds to me like the two discussions are unrelated.

-Peter
Jul 18 '05 #29
Peter Hansen wrote:
Phil said Ocaml allowed multiple _ in tuple assignments but
that Python did not, while I attempted to correct that assertion by
showing that it in fact did.

David and you were discussing a case involving function languages,
which Python is not, where the use of multiple _ (which now has
syntactical meaning, as opposed to being just an "ignore this" by
convention) is allowed.

Sounds to me like the two discussions are unrelated.


More or less so. It was only a discussion on the etimology of the
underscore convention. :-)

--
Ciao,
Matteo
Jul 18 '05 #30
Matteo Dell'Amico wrote:
Peter Hansen wrote:
Sounds to me like the two discussions are unrelated.


More or less so. It was only a discussion on the etimology of the
underscore convention. :-)


In that case they would be related, but is this any more than
supposition on your part? Is the use of _ as a throw-away in
for loops, and perhaps even in the interpreter as "last result",
definitely descended from its wildcard usage in functional
languages (or, at least, Ocaml)?

-Peter
Jul 18 '05 #31
On Thu, 29 Jul 2004, Peter Hansen wrote:
In that case they would be related, but is this any more than
supposition on your part? Is the use of _ as a throw-away in
for loops, and perhaps even in the interpreter as "last result",
definitely descended from its wildcard usage in functional
languages (or, at least, Ocaml)?


I'm pretty sure they're both descended from the use of _ as both a
throw-away and a wildcard in Prolog, as another poster pointed out.

For reference, Prolog was born in 1970, OCaml was born in 1996 (with roots
dating back to ML in 1983), and Python was born in 1991. (Data gleaned
from the Programming Language Genealogy Project at everything2.com.)

Jul 18 '05 #32
Christopher T King wrote:
On Thu, 29 Jul 2004, Peter Hansen wrote:
In that case they would be related, but is this any more than
supposition on your part? Is the use of _ as a throw-away in
for loops, and perhaps even in the interpreter as "last result",
definitely descended from its wildcard usage in functional
languages (or, at least, Ocaml)?


I'm pretty sure they're both descended from the use of _ as both a
throw-away and a wildcard in Prolog, as another poster pointed out.


I'm just as unsure about any of that. It seems more likely to
me that a number of people have independently found _ to be a handy
"anonymous" variable in different situations, and that trying to find
links to analogous usage in other languages is largely speculative.

Of course, that said, we'll probably hear shortly from someone
channelling the person who added it to the interpreter as the
"last result" name, contra-dicting me. :-)

-Peter
Jul 18 '05 #33
Peter Hansen wrote:
I'm just as unsure about any of that. It seems more likely to
me that a number of people have independently found _ to be a handy
"anonymous" variable in different situations, and that trying to find
links to analogous usage in other languages is largely speculative.
It would surprise me if the three were unrelated... there are
similarities between prolog's unification, ML's pattern matching and
python's tuple unpacking (even if the latter is considerably simpler and
less powerful), and note that the specific meaning of _ - both in Prolog
and in ML-like languages - is "throw away": if I'm not mistaken, you can
always replace an underscore with a new unused variable.
Of course, that said, we'll probably hear shortly from someone
channelling the person who added it to the interpreter as the
"last result" name, contra-dicting me. :-)


I see this one as a totally unrelated meaning, similar to perl's $_. I'm
waiting to be contradicted, too. :-)

--
Ciao,
Matteo
Jul 18 '05 #34
In article <41***************@alcyone.com>, Erik Max Francis wrote:
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, _).


In Python, it's possible to use _ multiple times in the same expression,
too. I guess there's no obvious reason why this shouldn't work, but I
discovered the following tuple-unpacking idiom recently:
for _, val, _ in ((1, 2, 3), (4, 5, 6), (7, 8, 9)):

.... print val
....
2
5
8

--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.

"When the country is confused and in chaos, information scientists appear."
Librarian's Lao Tzu: http://www.geocities.com/onelibrarian.geo/lao_tzu.html
Jul 18 '05 #35

"Dave Benjamin" <ra***@lackingtalent.com> wrote in message
news:slrncgj6j3.vte.ra***@lackingtalent.com...
In Python, it's possible to use _ multiple times in the same expression,
In Python, _ is a (non-keyword) name like any other. It can be used like
any other name. In interactive mode, it is the default name bound to bare
expressions, but it is still just a name.
too. I guess there's no obvious reason why this shouldn't work, but I
discovered the following tuple-unpacking idiom recently:
for _, val, _ in ((1, 2, 3), (4, 5, 6), (7, 8, 9)): ... print val
...
2
5
8


So does
for a,v,a in [[1,2,3], [4,5,6]]: print v

....
2
5

too much fuss over simplicity yours

Terry J. Reedy

Jul 18 '05 #36
Dave Benjamin <ra***@lackingtalent.com> writes:
In Python, it's possible to use _ multiple times in the same expression,


There is, however, one objection to the use of _ as a placeholder for
a dummy variable: it is used by the gettext module. So if a program
may be subject to internationalization, it is advisable to keep this
name reserved, or you may run into problems.

Jul 18 '05 #37

Heike> Dave Benjamin <ra***@lackingtalent.com> writes:
In Python, it's possible to use _ multiple times in the same expression,


Heike> There is, however, one objection to the use of _ as a placeholder
Heike> for a dummy variable: it is used by the gettext module. So if a
Heike> program may be subject to internationalization, it is advisable
Heike> to keep this name reserved, or you may run into problems.

Only if you use it as both a placeholder variable and call it as a function
within the same function, or have the misfortune to declare

global _

in some function where it's used as a placeholder in a module whose other
functions call _("some string").

Skip
Jul 18 '05 #38

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Steve Richter | last post: by
3 posts views Thread by RobertTG | last post: by
92 posts views Thread by Heinrich Pumpernickel | last post: by
45 posts views Thread by loudking | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.