views:

1702

answers:

7

Is is possible to do this;

for i in range(some_number):
    #do something

without the i? If you just want to do something x amount of times and don't need the iterator.

+10  A: 

Off the top of my head, no.

I think the best you could do is something like this:

def loop(f,n):
    for i in xrange(n): f()

loop(lambda: <insert expression here>, 5)

But I think you can just live with the extra i variable.

Here is the option to use the _ variable, which in reality, is just another variable.

for _ in range(n):
    do_something()

Note that _ is assigned the last result that returned in an interactive python session:

>>> 1+2
3
>>> _
3

For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.

>>> for _ in xrange(10): pass
...
>>> _
9
>>> 1+2
3
>>> _
9

And according to python grammar, it is an acceptable variable name:

identifier ::= (letter|"_") (letter | digit | "_")*

Unknown
"But I think you can just live with the extra "i"" Yeah it is just an academic point.
James McMahon
@nemo, you can try doing for _ in range(n): if you don't want to use alphanumeric names.
Unknown
Is _ a variable in that case? Or is that something else in Python?
James McMahon
It's a variable.
Nikhil Chelliah
@nemo Yes its just an acceptable variable name. In the interpreter, it is automatically assigned the last expression you made.
Unknown
Unknown if you edit all the information from your comments into your answer I'll mark it as the answer as there is the most information here.
James McMahon
@ nemo ok thanks! I'll do so.
Unknown
@Unknown, thank you for the answer. I just like to have all the information from the comments aggregated in the answer, not so much for myself, but for people you may look at the question in the future. I think of stack overflow as wiki more then anything else.
James McMahon
@nemo I'll make this post a wiki then.
Unknown
Oh by wiki I just meant keeping things organized as a way for people to find canonical information quickly using say Google. Sorry I just watched Joel's tech talk on SO and I am rambling.
James McMahon
but it does exactly the same, and `_` is still a variable, what's the point?
kurczak
+12  A: 

The general idiom for assigning to a value that isn't used is to name it _.

for _ in range(times):
    do_stuff()
Ryan
A: 

May be answer would depend on what problem you have with using iterator? may be use

i = 100
while i:
    print i
    i-=1

or

def loop(N, doSomething):
    if not N:
        return
    print doSomething(N)
    loop(N-1, doSomething)

loop(100, lambda a:a)

but frankly i see no point in using such approaches

Anurag Uniyal
+10  A: 

You may be looking for

for _ in itertools.repeat(None, times): ...

this is THE fastest way to iterate times times in Python.

Alex Martelli
I wasn't concerned with performance, I just was curious if there was a terser way to write the statement. While I have been using Python sporadically for about 2 years now I still feel there is a lot I am missing. Itertools is one of those things, thank you for the information.
James McMahon
That's interesting, I wasn't aware of that. I just took a look at the itertools docs; but I wonder why is this faster than just using range or xrange?
blackkettle
Yeah why not just optimize range?
James McMahon
@blackkettle: it's faster because it doesn't need to return the current iteration index, which is a measurable part of the cost of xrange (and Python 3's range, which gives an iterator, not a list). @nemo, range is as optimized as it can be, but needing to build and return a list is inevitably heavier work than an iterator (in Py3, range does return an iterator, like Py2's xrange; backwards compatibility doesn't permit such a change in Py2), especially one that doesn't need to return a varying value.
Alex Martelli
itertools.repeat uses a counter just like xrange, so I still don't understand how it can be faster than xrange. Does it really matter what value the iterator yields: if it's None or an int (the counter)?
Cristian Ciupitu
@Cristian, yes, clearly preparing and returning a Python int every time, inc. gc work, does have a measurable cost -- using a counter _internally_ is no matter.
Alex Martelli
I understand now. The difference comes from the GC overhead, not from the "algorithm". By the way, I run a quick *timeit* benchmark and the speedup was ~1.42x.
Cristian Ciupitu
+10  A: 

What everyone suggesting you to use _ isn't saying is that _ is frequently used as a shortcut to one of the gettext functions, so if you want your software to be available in more than one language then you're best off avoiding using it for other purposes.

import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
Ignacio Vazquez-Abrams
Thanks I will keep that in mind.
James McMahon
+3  A: 

Here's a random idea that utilizes (abuses?) the data model.

class Counter(object):
  def __init__(self, val):
    self.val = val

  def __nonzero__(self):
    self.val -= 1
    return self.val >= 0

x = Counter(5)
while x:
  # Do something
  pass

I wonder if there is something like this in the standard libraries?

saffsd
The is an interesting approach. Never heard of __nonzero__ before.
James McMahon
A: 
t=0    
for _ in range (0, 10):
  print t
  t = t+1

OUTPUT:
0 1 2 3 4 5 6 7 9