[Tutor] Do something on list elements

Mats Wichmann mats at wichmann.us
Fri Jul 27 20:28:10 EDT 2018

On 07/27/2018 04:32 PM, Cameron Simpson wrote:
> On 27Jul2018 23:06, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:

>> 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 think this was an important point: use a list index only when the
actual value of the index is important, otherwise use the fact that a
list is iterable by just looping over the list itself without bothering
with indices... it's a powerful enough idea that C++. C# and other
languages picked it up.

> I use indices when I need to modify the elements of a list in place. The
> list comprehension makes a shiny new list. That is usually fine, but not
> always what is required.

True indeed, but in this case since the elements being modified are
strings, which are immutable and thus "modifying" a string creates a new
string, we're not really buying anything by not creating a new list of
those new strings along the way...

More information about the Tutor mailing list