Does anyone else use this little idiom?

James Matthews nytrokiss at gmail.com
Sun Feb 3 04:03:43 CET 2008


What i do is a simple range call. for i in range(number of times i want to
repeat something)

I guess it comes from my C days for(i=0;i<100;i++) { or in python for i in
range(99):

On Feb 3, 2008 3:34 AM, Roy Smith <roy at panix.com> wrote:

> In article
> <e82b13fe-0974-400f-ac5b-0583a86fd9e0 at q39g2000hsf.googlegroups.com>,
>  miller.paul.w at gmail.com wrote:
>
> > Ruby has a neat little convenience when writing loops where you don't
> > care about the loop index: you just do n.times do { ... some
> > code ... } where n is an integer representing how many times you want
> > to execute "some code."
> >
> > In Python, the direct translation of this is a for loop.  When the
> > index doesn't matter to me, I tend to write it as:
> >
> > for _ in xrange (1,n):
> >    some code
> >
> > An alternative way of indicating that you don't care about the loop
> > index would be
> >
> > for dummy in xrange (1,n):
> >    some code
> >
> > But I like using _ because it's only 1 character and communicates well
> > the idea "I don't care about this variable."
>
> Not to me.  If I read "for _ in ...", I wouldn't be quite sure what _ was.
> Is it some magic piece of syntax I've forgotten about?  Or something new
> added to language while I wasn't paying attention (I still consider most
> stuff added since 1.5 to be new-fangled :-)).  If I see "dummy", I know it
> means, "the language requires a variable here, but the value is not
> needed".
>
> > 1. It might be a little jarring to people not used to it.  I do admit
> > it looks pretty strange at first.
> >
> > 2. The variable _ has special meaning at the interactive interpreter
> > prompt.  There may be some confusion because of this.
>
> Wow, I didn't even know about #2.  Now you see what I mean about "some
> magic syntax"?  Surely, between, "It looks strange", and "there may be
> some
> confusion", that's enough reason not to use it?
>
> But, more to the point, I'd try to find variable name which described why
> I
> was looping, even if I didn't actually use the value in the loop body:
>
> for number_that_you_shall_count_to in xrange(3):
>   print "Whaaaaaaa"
>  --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080203/ffae2a6c/attachment.html>


More information about the Python-list mailing list