[Tutor] A dictionary question

Alan Gauld alan.gauld at yahoo.co.uk
Sat Nov 20 04:03:00 EST 2021


On 20/11/2021 00:48, Phil wrote:
> 
>> please start writing standard Python for loops, e.g. :-
>>
>> for row in row_list:
>>     print(row, end=' ')
> 
> for i in range(len(row_list)):
>      print(row_list[i], end=' ')
> 
> The result is the same, however, I suppose it does matter 

The code is easier to read and more reliable, easier to maintain.
(It's less liable to index errors) It's also more Pythonic so
other Python programmers (and probably even you in 6 months
time) will understand it faster.

But it also makes a difference to performance since using
indexes Python has to do a lot of extra work finding the
element each time it's accessed. So, although you won't notice
the difference in 99% of normal code if you are trying to
do something performance intensive or on very large lists
it will make a difference.

Finally, there is the matter of credibility. Posting code
like this will immediately mark you out as a beginner in
the eyes of experienced python coders and so they will
tend to respond to any questions on that basis. They won't
be deliberately patronising but it will just be an automatic
assumption if they see an indexed for loop.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list