469,290 Members | 1,872 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

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

for loop without variable

Hi. I'd like to be able to write a loop such as:
for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint
and it complains about the unused variable i. I can achieve the above
with more lines of code like:
i = 0
while (i != 10):
i += 1
Is there a concise way to accomplish this without adding extra lines
of codes? Thanks in advance for your help.
Jan 9 '08 #1
35 19115
erik gartz schrieb:
Hi. I'd like to be able to write a loop such as:
for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint
and it complains about the unused variable i. I can achieve the above
with more lines of code like:
i = 0
while (i != 10):
i += 1
Is there a concise way to accomplish this without adding extra lines
of codes? Thanks in advance for your help.
The underscore is used as "discarded" identifier. So maybe
for _ in xrange(10):
...
works.

Diez
Jan 9 '08 #2
erik gartz schrieb:
Hi. I'd like to be able to write a loop such as:
for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint
and it complains about the unused variable i.
Pychecker won't complain if you rename 'i' to '_', IIRC:

for _ in range(10):
pass

Thomas

Jan 9 '08 #3
"Diez B. Roggisch" <de***@nospam.web.dewrites:
The underscore is used as "discarded" identifier. So maybe

for _ in xrange(10):
...
The problem with the '_' name is that it is already well-known and
long-used existing convention for an entirely unrelated purpose: in
the 'gettext' i18n library, the '_' function to get the
locally-translated version of a text string.

Since the number of programs that need to use something like 'gettext'
(and therefore use the '_' function) is likely only to increase, it
seems foolish to set one's program up for a conflict with that
established usage.

I've seen 'dummy' used as a "don't care about this value" name in
other Python code. That seems more readable, more explicit, and less
likely to conflict with existing conventions.

--
\ "It is forbidden to steal hotel towels. Please if you are not |
`\ person to do such is please not to read notice." -- Hotel |
_o__) sign, Kowloon, Hong Kong |
Ben Finney
Jan 9 '08 #4
On Jan 9, 11:17 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
"Diez B. Roggisch" <de...@nospam.web.dewrites:
The underscore is used as "discarded" identifier. So maybe
for _ in xrange(10):
...

The problem with the '_' name is that it is already well-known and
long-used existing convention for an entirely unrelated purpose: in
the 'gettext' i18n library, the '_' function to get the
locally-translated version of a text string.

Since the number of programs that need to use something like 'gettext'
(and therefore use the '_' function) is likely only to increase, it
seems foolish to set one's program up for a conflict with that
established usage.

I've seen 'dummy' used as a "don't care about this value" name in
other Python code. That seems more readable, more explicit, and less
likely to conflict with existing conventions.
Perhaps a "discarded" identifier should be any which is an underscore
followed by digits.

A single leading underscore is already used for "private" identifiers,
but they are usually an underscore followed by what would be a valid
identifier by itself, eg. "_exit".

The convention would then be:

2 underscores + valid_by_self + 2 underscores =special

underscore + valid_by_self =private

underscore + invalid_by_self =dummy
Jan 10 '08 #5
On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote:
Hi. I'd like to be able to write a loop such as:
for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint and
it complains about the unused variable i ...
What does that loop do? (Not the loop you posted, but the "real" loop
in your application.) Perhaps python has another way to express what
you're doing.

For example, if you're iterating over the elements of an array, or
through the lines of a file, or the keys of a dictionary, the "in"
operator may work better:

for thing in array_or_file_or_dictionary:
do_something_with(thing)

HTH,
Dan

--
Dan Sommers A death spiral goes clock-
<http://www.tombstonezero.net/dan/ wise north of the equator.
Atoms are not things. -- Werner Heisenberg -- Dilbert's PHB
Jan 10 '08 #6
On Jan 9, 8:35 pm, Dan Sommers <m...@privacy.netwrote:
On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote:
Hi. I'd like to be able to write a loop such as:
for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint and
it complains about the unused variable i ...

What does that loop do? (Not the loop you posted, but the "real" loop
in your application.) Perhaps python has another way to express what
you're doing.

For example, if you're iterating over the elements of an array, or
through the lines of a file, or the keys of a dictionary, the "in"
operator may work better:

for thing in array_or_file_or_dictionary:
do_something_with(thing)

HTH,
Dan

--
Dan Sommers A death spiral goes clock-
<http://www.tombstonezero.net/dan/ wise north of the equator.
Atoms are not things. -- Werner Heisenberg -- Dilbert's PHB
The loop performs some actions with web services. The particular
iteration I'm on isn't important to me. It is only important that I
attempt the web services that number of times. If I succeed I
obviously break out of the loop and the containing function (the
function which has the loop in it) returns True. If all attempts fail
the containing loop returns False.

I guess based on the replies of everyone my best bet is to leave the
code the way it is and suck up the warning from pylint. I don't want
to turn the warning off because catching unused variables in the
general is useful to me. Unfortunately, I don't *think* I can shut the
warning for that line or function off, only for the entire file.
Pylint gives you a rating of your quality of code which I think is
really cool. This is a great motivation and helps me to push to
"tighten the screws". However it is easy to get carried away with your
rating.:-)
Jan 10 '08 #7
On Jan 9, 9:49 pm, erik gartz <eegun...@yahoo.comwrote:
The loop performs some actions with web services. The particular
iteration I'm on isn't important to me. It is only important that I
attempt the web services that number of times. If I succeed I
obviously break out of the loop and the containing function (the
function which has the loop in it) returns True. If all attempts fail
the containing loop returns False.
Do you think you could apply something like this:

def foo():print "fetching foo..."
actions = (foo,)*5
for f in actions:
f()

fetching foo...
fetching foo...
fetching foo...
fetching foo...
fetching foo...

...but not knowing your specific implementation, I may be off the wall
here.

Cheers,
-Basilisk96
Jan 10 '08 #8
On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote:
Hi. I'd like to be able to write a loop such as: for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint and
it complains about the unused variable i. I can achieve the above with
more lines of code like:
i = 0
while (i != 10):
i += 1
Is there a concise way to accomplish this without adding extra lines of
codes? Thanks in advance for your help.

IIRC, in pylint you can turn off checking for a particular symbol. I had
to edit a .pylintrc file (location may vary on Windows) and there was a
declaration in the file that listed symbols to ignore.

Last time I bothered running it, I added "id" to that list, since I use
it often (bad habit) and almost never use the builtin id, but still
wanted shadowing warnings for other symbols.
Carl Banks
Jan 10 '08 #9
erik gartz <ee******@yahoo.comwrites:
The loop performs some actions with web services. The particular
iteration I'm on isn't important to me. It is only important that I
attempt the web services that number of times. If I succeed I
obviously break out of the loop and the containing function (the
function which has the loop in it) returns True. If all attempts
fail the containing loop returns False.
When you have iteration requirements that don't seem to fit the
built-in types (lists, dicts, generators etc.), turn to 'itertools'
<URL:http://www.python.org/doc/lib/module-itertoolsin the standard
library.
>>from itertools import repeat
>>def foo():
... import random
... print "Trying ..."
... success = random.choice([True, False])
... return success
...
>>max_attempts = 10
for foo_attempt in repeat(foo, max_attempts):
... if foo_attempt():
... break
...
Trying ...
Trying ...
Trying ...
Trying ...
Trying ...
Trying ...
>>>
Note that this is possibly more readable than 'for foo_attempt in
[foo] * max_attempts", and is more efficient for large values of
'max_attempts' because 'repeat' returns an iterator instead of
actually allocating the whole sequence.
I guess based on the replies of everyone my best bet is to leave the
code the way it is and suck up the warning from pylint.
I think your intent -- "repeat this operation N times" -- is better
expressed by the above code, than by keeping count of something you
don't actually care about.
I don't want to turn the warning off because catching unused
variables in the general is useful to me.
Agreed.

--
\ "Dyslexia means never having to say that you're ysror." |
`\ —anonymous |
_o__) |
Ben Finney
Jan 10 '08 #10
On Wed, 9 Jan 2008 18:49:36 -0800 (PST) erik gartz <ee******@yahoo.comwrote:
The loop performs some actions with web services. The particular
iteration I'm on isn't important to me. It is only important that I
attempt the web services that number of times. If I succeed I
obviously break out of the loop and the containing function (the
function which has the loop in it) returns True. If all attempts fail
the containing loop returns False.
It sounds to me like your counter variable actually has meaning, but
you've hidden that meaning by giving it the meaningless name "i". If
you give it a meaningful name, then there's an obvious way to do it
(which you listed yourself):

while retries_left:
if this_succeeds():
return True
retries_left -= 1

return False

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 10 '08 #11
Sam
Unfortunately, I don't *think* I can shut the
warning for that line or function off, only for the entire file.
Pylint gives you a rating of your quality of code which I think is
wrong :)

# pylint: disable-msg=XXXXX will only impact the current line!

$ cat -n dummy.py
1 for i in range(2): # pylint: disable-msg=W0612
2 print "foo"
3 for i in range(2):
4 print "foo"

pylint will not generate a warning on line 1, but will on line 3!

Cheers.

Sam


Jan 10 '08 #12
Mike Meyer <mw***********************@mired.orgwrites:
It sounds to me like your counter variable actually has meaning,
It depends how the code is written. In the example such as:

for meaningless_variable in xrange(number_of_attempts):
...

the loop variable really has no meaning. Rewriting this code only to
appease pylint is exactly that, it has nothing with making the code
more readable.
you've hidden that meaning by giving it the meaningless name "i". If
you give it a meaningful name, then there's an obvious way to do it
(which you listed yourself):

while retries_left:
[...]

This loop contains more code and hence more opportunities for
introducing bugs. For example, if you use "continue" anywhere in the
loop, you will do one retry too much.
Jan 10 '08 #13
-On [20080110 00:21], Ben Finney (bi****************@benfinney.id.au) wrote:
>The problem with the '_' name is that it is already well-known and
long-used existing convention for an entirely unrelated purpose: in
the 'gettext' i18n library, the '_' function to get the
locally-translated version of a text string.
The same applies for Babel (http://babel.edgewall.org/) where we have _() in
similar vein to the gettext implementation.

--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org/ asmodai
イェルーン ラウフ*ック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
With a nuclear fire of Love in our Hearts, rest easy baby, rest easy...
Jan 10 '08 #14
Hallchen!

Ben Finney writes:
"Diez B. Roggisch" <de***@nospam.web.dewrites:
>The underscore is used as "discarded" identifier. So maybe

for _ in xrange(10):
...

The problem with the '_' name is that it is already well-known and
long-used existing convention for an entirely unrelated purpose:
in the 'gettext' i18n library, the '_' function to get the
locally-translated version of a text string.
Right, that's because I've used "__" where not all returning values
are interesing to me such as

a, b, __ = function_that_returns_three_values(x, y)

However, in loops, I prefer real names, even if the loop variable
isn't used outside.

Tsch,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: br*****@jabber.org
(See http://ime.webhop.org for further contact info.)
Jan 10 '08 #15
Torsten Bronger wrote:
>Hallchen!

Ben Finney writes:
>"Diez B. Roggisch" <de***@nospam.web.dewrites:
>>The underscore is used as "discarded" identifier. So maybe

for _ in xrange(10):
...

The problem with the '_' name is that it is already well-known and
long-used existing convention for an entirely unrelated purpose:
in the 'gettext' i18n library, the '_' function to get the
locally-translated version of a text string.

Right, that's because I've used "__" where not all returning values
are interesing to me such as

a, b, __ = function_that_returns_three_values(x, y)
Variable name "dummy" serves the same purpose, such as:

a, b, dummy = function_that_returns_three_values(x, y)

According to http://linux.die.net/man/1/pylint it is also possible to use the
option

--dummy-variables-rgx=<regexp>

to further specify which variable not to report as unused. As far as I can
tell, it defaults to '_|dummy'.

..david
Jan 10 '08 #16
erik gartz <ee******@yahoo.comwrote:
Hi. I'd like to be able to write a loop such as:
for i in range(10):
pass
but without the i variable. The reason for this is I'm using pylint
and it complains about the unused variable i. I can achieve the above
with more lines of code like:
i = 0
while (i != 10):
i += 1
Is there a concise way to accomplish this without adding extra lines
of codes? Thanks in advance for your help.

Google for: pylint unused

It pointed me at:
Question:
I've a function / method which is a callback where I do not have any
control on received argument, and pylint is complaining about unused
arguments. What can I do to avoid those warnings ?

Answer:
prefix (ui) the callback's name by cb_, as in cb_onclick(...). By doing
so arguments usage won't be checked. Another solution is to use one of
the name defined in the "dummy-variables" configuration variable for
unused argument ("_" and "dummy" by default).
http://www.iaeste.or.at/doc/python2..../html/FAQ.html

So it looks like you can use 'dummy' or add any other names you want to the
configuration.
Jan 10 '08 #17
Hallchen!

Da***********@sweco.no writes:
Torsten Bronger wrote:
>[...]

Right, that's because I've used "__" where not all returning
values are interesing to me such as

a, b, __ = function_that_returns_three_values(x, y)

Variable name "dummy" serves the same purpose, such as:

a, b, dummy = function_that_returns_three_values(x, y)
Granted, but my rationale is that "__" is less visible in the source
code, so there is more emphasis on the actually interesting
variables.

Tsch,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: br*****@jabber.org
(See http://ime.webhop.org for further contact info.)
Jan 10 '08 #18
Torsten Bronger writes:
>Da***********@sweco.no writes:
>Torsten Bronger wrote:
>>[...]

Right, that's because I've used "__" where not all returning
values are interesing to me such as

a, b, __ = function_that_returns_three_values(x, y)

Variable name "dummy" serves the same purpose, such as:

a, b, dummy = function_that_returns_three_values(x, y)

Granted, but my rationale is that "__" is less visible in the source
code, so there is more emphasis on the actually interesting
variables.
I guess it's a matter of preference. Personally, I find "dummy" to be more
explicit, and hence more readable for those that that will read my code
later. YMMV.

Regards,
..david
Jan 10 '08 #19
On Thu, 10 Jan 2008 08:42:16 +0100 Hrvoje Niksic <hn*****@xemacs.orgwrote:
Mike Meyer <mw***********************@mired.orgwrites:
It sounds to me like your counter variable actually has meaning,
It depends how the code is written. In the example such as:

for meaningless_variable in xrange(number_of_attempts):
...

the loop variable really has no meaning. Rewriting this code only to
appease pylint is exactly that, it has nothing with making the code
more readable.
Except in this case, the variable *has* a meaning. You've just chosen
to obfuscate it.
you've hidden that meaning by giving it the meaningless name "i". If
you give it a meaningful name, then there's an obvious way to do it
(which you listed yourself):

while retries_left:
[...]

This loop contains more code and hence more opportunities for
introducing bugs. For example, if you use "continue" anywhere in the
loop, you will do one retry too much.
All correct - and I'm a big fan of minimizing code, as code you don't
write has no bugs in it. But you can still show the meaning of this
"meaningless" variable:

for number_of_attempts in xrange(maximum_attempts):

Of course, the OP's request is a better solution: since he doesn't
actually need the variable, removing it completely means there's one
less variable, which is one less thing you can set to the wrong value.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 10 '08 #20
On Jan 9, 10:55 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
erik gartz <eegun...@yahoo.comwrites:
The loop performs some actions with web services. The particular
iteration I'm on isn't important to me. It is only important that I
attempt the web services that number of times. If I succeed I
obviously break out of the loop and the containing function (the
function which has the loop in it) returns True. If all attempts
fail the containing loop returns False.

When you have iteration requirements that don't seem to fit the
built-in types (lists, dicts, generators etc.), turn to 'itertools'
<URL:http://www.python.org/doc/lib/module-itertoolsin the standard
library.
>>from itertools import repeat
>>def foo():
... import random
... print "Trying ..."
... success = random.choice([True, False])
... return success
...
>>max_attempts = 10
>>for foo_attempt in repeat(foo, max_attempts):
... if foo_attempt():
... break
...
Trying ...
Trying ...
Trying ...
Trying ...
Trying ...
Trying ...
>>>

Note that this is possibly more readable than 'for foo_attempt in
[foo] * max_attempts", and is more efficient for large values of
'max_attempts' because 'repeat' returns an iterator instead of
actually allocating the whole sequence.
I guess based on the replies of everyone my best bet is to leave the
code the way it is and suck up the warning from pylint.

I think your intent -- "repeat this operation N times" -- is better
expressed by the above code, than by keeping count of something you
don't actually care about.
I don't want to turn the warning off because catching unused
variables in the general is useful to me.

Agreed.

--
\ "Dyslexia means never having to say that you're ysror." |
`\ --anonymous |
_o__) |
Ben Finney
Neat! That is the best solution I've seen so far. I should definitely
dig into the itertools module more often.

Cheers,
-Basilisk96
Jan 11 '08 #21
Hrvoje Niksic wrote:
Mike Meyer <mw***********************@mired.orgwrites:
>It sounds to me like your counter variable actually has meaning,

It depends how the code is written. In the example such as:

for meaningless_variable in xrange(number_of_attempts):
...

the loop variable really has no meaning. Rewriting this code only to
appease pylint is exactly that, it has nothing with making the code
more readable.
>you've hidden that meaning by giving it the meaningless name "i". If
you give it a meaningful name, then there's an obvious way to do it
(which you listed yourself):

while retries_left:
[...]

This loop contains more code and hence more opportunities for
introducing bugs. For example, if you use "continue" anywhere in the
loop, you will do one retry too much.
I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])

This caused me to wonder why Python does not have a "foreach" statement (and
also why has it not come up in this thread)? I realize the topic has probably
been beaten to death in earlier thread(s), but does anyone have the short answer?
Jan 11 '08 #22
On Behalf Of Marty
I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])

This caused me to wonder why Python does not have a "foreach"
statement (and also why has it not come up in this thread)?
I realize the topic has probably been beaten to death in
earlier thread(s), but does anyone have the short answer?
data_out = [[] for item in data_in]

Regards,
Ryan Ginstrom

Jan 11 '08 #23
On Thu, 10 Jan 2008 22:36:56 -0500 Marty <ma*****@earthlink.netwrote:
I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])
More succinctly:

data_out = []
for _ in data_in:
data_out.append([])

Or, as has already been pointed out:

data_out = [[] for _ in data_in]
This caused me to wonder why Python does not have a "foreach" statement (and
also why has it not come up in this thread)? I realize the topic has probably
been beaten to death in earlier thread(s), but does anyone have the short answer?
But I'm curious - what's the difference between the "foreach" you have
in mind and the standard python "for"?

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 11 '08 #24
On Jan 10, 10:36 pm, Marty <mart...@earthlink.netwrote:
Hrvoje Niksic wrote:
Mike Meyer <mwm-keyword-python.b4b...@mired.orgwrites:
It sounds to me like your counter variable actually has meaning,
It depends how the code is written. In the example such as:
for meaningless_variable in xrange(number_of_attempts):
...
the loop variable really has no meaning. Rewriting this code only to
appease pylint is exactly that, it has nothing with making the code
more readable.
you've hidden that meaning by giving it the meaningless name "i". If
you give it a meaningful name, then there's an obvious way to do it
(which you listed yourself):
while retries_left:
[...]
This loop contains more code and hence more opportunities for
introducing bugs. For example, if you use "continue" anywhere in the
loop, you will do one retry too much.

I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])

This caused me to wonder why Python does not have a "foreach" statement (and
also why has it not come up in this thread)? I realize the topic has probably
been beaten to death in earlier thread(s), but does anyone have the short answer?
Pythons `for' essentially is foreach. The code below does the same
thing as what you have posted does. Actually, I've found that if you
find yourself ever doing range(len(data_in)) in python, it is time to
take a second look.

data_out = []
for x in data_in:
data_out.append([])

`range' is just a function that returns a list.

Matt

Jan 11 '08 #25
erik gartz <ee******@yahoo.comwrites:
The loop performs some actions with web services. The particular
iteration I'm on isn't important to me. It is only important that I
attempt the web services that number of times. If I succeed I
obviously break out of the loop and the containing function (the
function which has the loop in it) returns True. If all attempts fail
the containing loop returns False.
This uses an index var, but doesn't leak it outside the genexp, so
I don't know what pylint would say (untested):

def f():
return any(attempt_service() for i in xrange(10))

I think the above is pretty natural. If you really insist on not
using any variables, the below might work (untested):

from itertools import imap, repeat

def f():
return any(imap(apply, repeat(attempt_service, 10)))

it just seems way too obscure though. Python style seems to favor
spewing extra variables around.
Jan 11 '08 #26
Mike Meyer <mw***********************@mired.orgwrites:
data_out = [[] for _ in data_in]
...
But I'm curious - what's the difference between the "foreach" you have
in mind and the standard python "for"?
The "for" loop, like the list comprehension, pollutes the namespace
with an index variable that's not used for anything. I prefer genexps:

data_out = list([] for x in data_in)
Jan 11 '08 #27
On Thu, 10 Jan 2008 22:36:56 -0500, Marty wrote:
I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])

This caused me to wonder why Python does not have a "foreach" statement
(and also why has it not come up in this thread)? I realize the topic
has probably been beaten to death in earlier thread(s), but does anyone
have the short answer?
Most languages that have "foreach" use it the same way Python uses
"for". The reason they use "foreach" instead of plain "for" is often
because they have a separate for statement that mimic C's for.

Perhaps you're wondering why there is no syntax for looping a given
number of times. (Languages that have this feature, e.g., Ada, often to
use "repeat" as the keyword.)

1. Looping a fixed number of times is quite uncommon.
2. A syntax for it buys you almost nothing.
Carl Banks
Jan 11 '08 #28
Mike Meyer wrote:
On Thu, 10 Jan 2008 22:36:56 -0500 Marty <ma*****@earthlink.netwrote:
>I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])

More succinctly:

data_out = []
for _ in data_in:
data_out.append([])

Or, as has already been pointed out:

data_out = [[] for _ in data_in]
That's nice.
>
>This caused me to wonder why Python does not have a "foreach" statement (and
also why has it not come up in this thread)? I realize the topic has probably
been beaten to death in earlier thread(s), but does anyone have the short answer?

But I'm curious - what's the difference between the "foreach" you have
in mind and the standard python "for"?

<mike
For example, I thought the python "equivalent" of perl's foreach might be:

data_out = [[] foreach data_in]

Trying to answer my own question, if it comes down to a choice between a unique
statement v. the anonymous variable "_", then I guess I can see why Python did
it this way.
Jan 11 '08 #29
On Jan 10, 10:36 pm, Marty <mart...@earthlink.netwrote:
Hrvoje Niksic wrote:
Mike Meyer <mwm-keyword-python.b4b...@mired.orgwrites:
It sounds to me like your counter variable actually has meaning,
It depends how the code is written. In the example such as:
for meaningless_variable in xrange(number_of_attempts):
...
the loop variable really has no meaning. Rewriting this code only to
appease pylint is exactly that, it has nothing with making the code
more readable.
you've hidden that meaning by giving it the meaningless name "i". If
you give it a meaningful name, then there's an obvious way to do it
(which you listed yourself):
while retries_left:
[...]
This loop contains more code and hence more opportunities for
introducing bugs. For example, if you use "continue" anywhere in the
loop, you will do one retry too much.

I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])

This caused me to wonder why Python does not have a "foreach" statement (and
also why has it not come up in this thread)? I realize the topic has probably
been beaten to death in earlier thread(s), but does anyone have the short answer?
But it does:

data_in = (1,2,3,4,5)
data_out = []

data_out += [[] for blah in data_in]

print data_out
[[], [], [], [], []]
Cheers,
-Basilisk96
Jan 11 '08 #30
On Fri, 11 Jan 2008 01:48:43 -0500 Marty <ma*****@earthlink.netwrote:
Mike Meyer wrote:
This caused me to wonder why Python does not have a "foreach" statement (and
also why has it not come up in this thread)? I realize the topic has probably
been beaten to death in earlier thread(s), but does anyone have the short answer?
But I'm curious - what's the difference between the "foreach" you have
in mind and the standard python "for"?
For example, I thought the python "equivalent" of perl's foreach might be:

No, python's equivalent of Perl's foreach is "for". I.e.

foreach $var (@list)

does the same thing as Python's

for var in list

(except Perl gets the scoping right).

Maybe you're thinking of Perls "default variable" feature (I don't
know what else to call it), which implicitly uses $_ as a variable in
any number of places if you fail to provide a variable? So that you
can say:

foreach (@list)

and apparently not have to use a variable, except it implicitly uses $_.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 11 '08 #31
Paul Rubin wrote:
it just seems way too obscure though. Python style seems to favor
spewing extra variables around.
that's because (local) variables have near-zero cost, and zero overhead.
use as many as you want, and reuse them as often as you want to.

(and if you use sane naming conventions, the risk for collisions is near
zero as well).

</F>

Jan 11 '08 #32
Fredrik Lundh <fr*****@pythonware.comwrites:
(and if you use sane naming conventions, the risk for collisions is
near zero as well).
I haven't felt that way, I'm always worried about clobbering something
by leaking a variable. Maybe collisions don't really happen much, but
it's always seemed cleaner to me to use the most restricted scopes
possible just to minimize or eliminate the possibility. This is
especially attractie in a language like Python, with no declarations
and no compile-time type safety.
Jan 11 '08 #33
Marty:
I recently faced a similar issue doing something like this:

data_out = []
for i in range(len(data_in)):
data_out.append([])
Another way to write this is
data_out = [[]] * len(data_in)

Neil
Jan 11 '08 #34
On Fri, 11 Jan 2008 22:18:22 GMT Neil Hodgson <ny*****************@gmail.comwrote:
Marty:
I recently faced a similar issue doing something like this:
data_out = []
for i in range(len(data_in)):
data_out.append([])

Another way to write this is
data_out = [[]] * len(data_in)
Not quite. All the other variants give you 23 empty lists. That one
gives you 23 references to one list:
>>x = [[] for _ in range(23)]
x[1].append(23)
x
[[], [23], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>x = [[]] * 23
x[1].append(23)
x
[[23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23], [23]]
<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 11 '08 #35
>I recently faced a similar issue doing something like this:
>>
data_out = []
for i in range(len(data_in)):
data_out.append([])

Another way to write this is
data_out = [[]] * len(data_in)
....if you're willing to put up with this side-effect:
>>data_in = range(10)
data_out = [[]] * len(data_in)
data_out
[[], [], [], [], [], [], [], [], [], []]
>>data_out[0].append('hello')
data_out
[['hello'], ['hello'], ['hello'], ['hello'], ['hello'],
['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

For less flakey results:
>>data_out = [[] for _ in data_in]
data_out
[[], [], [], [], [], [], [], [], [], []]
>>data_out[0].append('hello')
data_out
[['hello'], [], [], [], [], [], [], [], [], []]
-tkc
Jan 11 '08 #36

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.