Does anyone else use this little idiom?

Eduardo O. Padoan eduardo.padoan at gmail.com
Tue Feb 5 22:12:29 CET 2008


On Feb 5, 2008 1:30 PM, Nick Craig-Wood <nick at craig-wood.com> wrote:
> miller.paul.w at gmail.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
>
> I use pychecker a lot.  It views variables called [ '_', 'unused',
> 'empty', 'dummy' ] as names to ignore if they haven't been used.
>
> So according to pychecker '_' and 'dummy' would both be OK.
>
> As for me personally, I usually use '_' but sometimes use 'dummy'
> depending on the surrounding code.
>
> Note that this idiom is fairly common in python too
>
>  wanted, _, _, _, also_wanted = a_list
>
> which looks quite neat to my eyes.
>

BTW and FWIW, in Py3k you can do:

 wanted, *_, also_wanted = a_list

http://www.python.org/dev/peps/pep-3132/

-- 
http://www.advogato.org/person/eopadoan/
Bookmarks: http://del.icio.us/edcrypt



More information about the Python-list mailing list