[python-advocacy] example code

Carl Karsten carl at personnelware.com
Thu Nov 12 17:00:58 CET 2009


2009/11/12 Tarek Ziadé <ziade.tarek at gmail.com>:
> On Thu, Nov 12, 2009 at 3:39 PM, Ray Allen <rayallen153 at googlemail.com> wrote:
> [..]
>>
>> # Loop through list
>> count = 1
>> print "Python is ... "
>> for each in python:
>>     print count,each
>>     count += 1
>
> I'd replace this bloc by:
>
> # Loop through list
> print "Python is ... "
> for index, each in enumerate(python):
>    print index + 1, each
>
> (using enumerate is much more pythonic than using a count variable)

I would avoid the counter.

I learned to iterate a list by using a counter as an index into the
list.  When I was shown that I didn't need the counter, I felt uneasy
- perhaps even in denial that this was a good thing - seemed like a
short cut.   Weeks or months later it hit me: The reason I needed it
in those other languages is because they didn't have this 'feature',
so the counter/index/item was a work around.

A few months ago someone getting started with python was asking me
~"why is the counter/index/item pattern so cumbersome?"  A:"Because
you normally don't need the counter."  I could see in his eyes the
exact same disbelief I had felt.

I think we should to focus on what makes python different.

-- 
Carl K


More information about the Advocacy mailing list