*Naming Conventions*

Michael Hoffman cam.ac.uk at mh391.invalid
Mon Jun 4 17:25:50 EDT 2007


Wildemar Wildenburger wrote:
> bruno.desthuilliers at gmail.com wrote:
>> On Jun 4, 12:20 am, Ninereeds <stephenhorne... at aol.com> wrote:
>>  
>>> First, for small loops with loop variables whose meaning is obvious
>>> from context, the most readable name is usually something like 'i' or
>>> 'j'.
>>>     
>>
>> 'i' and 'j' are the canonical names for for loops indices in languages
>> that don't support proper iteration over a sequence. Using them for
>> the iteration variable of a Python for loop (which is really a
>> 'foreach' loop) would be at best confusing.
>>
>>   
> 
> While that is true, I guess it is commonplace to use i, j, k and n 
> (maybe others) in constructs like
> 
> for i in range(len(data)):
>    do_stuff(data[i])
> 
> Or should the good python hacker do that differently? Hope not ;).

Well, yes, I would do:

for item in data:
    do_stuff(item)

or, if using enumerate:

for item_index, item in enumerate(data):
    do_stuff(item_index, item)

I agree with Bruno that i and j should be used only for indices, but I'm 
usually less terse than that.
-- 
Michael Hoffman



More information about the Python-list mailing list