Basic Nested Dictionary in a Loop

Terry Reedy tjreedy at
Sun Apr 2 18:51:14 EDT 2017

On 4/2/2017 1:59 PM, Ganesh Pal wrote:

 > 'someone' wrote
>> Whenever you feel the urge to write range(len(whatever)) -- resist that
>> temptation, and you'll end up with better Python code ;)

> Thanks for this suggestion but for my better understanding can explain
> this further even Steve did point the same mistake.

Before 2.2, one could only iterate through a sequence of integers, or 
something that pretended to be such.  So the way to iterate though a 
finite sequence of non-ints was

for i in range(len(seq)):
     item = seq[i]
     <do stuff with item>

The current iterator protocol allows one to separate item access or 
generation from item processing and to hide the former in an iterator. 
One then says in the header what collection of items one want to process 
and in what order (one at a time) and in the body what one wants to do 
with them.

for item in seq:  # items of seq in normal order
     <do stuff with item>

for item in iterable:  # not restricted to sequences, default order
     <do stuff with item>

Some other variations in the new form.

for item in reversed(iterable):  # finite collection in reversed order
     <do stuff with item>

for i, item in enumerate(seq):
     <do stuff with i and item>

for item1, item2 in zip(seq1, seq2):
      <do stuff with item1 and item2>

Terry Jan Reedy

More information about the Python-list mailing list