[Tutor] Do something on list elements

Cameron Simpson cs at cskk.id.au
Fri Jul 27 18:32:18 EDT 2018


On 27Jul2018 23:06, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 27/07/18 13:56, Valerio Pachera wrote:
>
>> l = ['unoX', 'dueX']
>> c = 0
>> for n in l:
>>         l[c] = l[c].replace('X','')
>>         c = c + 1
>> print (l)
>>
>> it works but I wonder if there's a better way to achieve the same.
>
>Yes, a much better way.
>
>for index, s in l:
>   l[index] = s.replace('X','')
>print(l)

I think you meant:

  for index, s in enumerate(l):

>But better still is a list comprehension:
>
>l = [s.replace('X','') for s in l)
>print(l)
>
>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. The list 
comprehension makes a shiny new list. That is usually fine, but not always what 
is required.

I also have (rare) occasions where an item wants know its own index. In that 
case one wants the index floating around so it can be attached to the item.

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:

  with open(filename) as f:
    for lineno, line in enumerate(f, 1):
      if badness:
        print("%s:%d: badness happened" % (filename, lineno), file=sys.stderr)
        continue
      ... process good lines ...

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list