is this pythonic?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Jul 21 10:30:04 EDT 2005


On Wed, 20 Jul 2005 16:30:10 -0400, Bill Mill wrote:

> On 7/20/05, Simon Brunning <simon.brunning at gmail.com> wrote:
>> On 7/20/05, Mage <mage at mage.hu> wrote:
>> > Or is there better way?
>> >
>> > for (i, url) in [(i,links[i]) for i in range(len(links))]:
>> 
>> for i, url in enumerate(links):
>> 
> 
> +2 for creating seeing a need and crafting a reasonable solution, but
> -1 for not reading the section on builtins to see if it existed
> already.

To see if *what* existed already?

It is well and good to say RTFM, but there are 697 subsections to the
Python Library reference, and if you don't know what you are looking for,
and beginners rarely are, it isn't obvious which is the right section to
read. And the Library Reference isn't even "the" manual: there is also the
global module reference and language reference.

If you already know what you are looking for, reading the manual is great
advice. Browsing the manual looking for interesting tidbits can even be
fun for a certain mindset. But if you don't know enough to know what to
look for, where in the 2000-odd sections of the Python references will
you find it?



> (As for its pythonicity, I would have recommended isolating it into a
> function and making it a generator:

It is easy to take this to extremes. It isn't necessary to isolate
everything into its own object, or class, or module. Too much
encapsulation is just as bad as too little.


> def my_enumerate(enumerable):
>     i = 0
>     for elt in enumerable:
>         yield (i, elt)
>         i += 1
> 
> for i, url in my_enumerate(links):
> 
> but it's not too bad as it is. Also, my function is completely
> untested - it's close to right though.)

What is the advantage of your function my_enumerate over the Python
built-in enumerate?


-- 
Steven.




More information about the Python-list mailing list