Does anyone else use this little idiom?

Roy Smith roy at panix.com
Sun Feb 3 03:34:52 CET 2008


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"



More information about the Python-list mailing list