[Tutor] Do something on list elements

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jul 27 19:24:41 EDT 2018


On 27/07/18 23:32, Cameron Simpson wrote:

>> for index, s in l:
>>   l[index] = s.replace('X','')
>> print(l)
> 
> I think you meant:
> 
>   for index, s in enumerate(l):

Oops, yes. Sorry.

>> In Python you very rarely need to resort to using indexes
>> to process the members of a collection. And even more rarely
>> do you need to manually increment the index.
> 
> I use indices when I need to modify the elements of a list in place. 

Yes, that's probably the most common use case, and
enumerate is the best way to do that.

> comprehension makes a shiny new list. That is usually fine, but not always what 
> is required.

>From a purist point of view its usually preferable but in
practice making copies of large data structures is usually
a bad idea.  In that case you are forced to resort to
enumerate, I agree.

> The other place I use enumerate in a big way is to track line numbers in files, 
> as context for error messages (either now or later). For example:

Yes, but then you don't use the index to access/process
the data. Its just providing context.


-- 
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