[Tutor] Do something on list elements

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jul 27 18:06:55 EDT 2018

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','')

But better still is a list comprehension:

l = [s.replace('X','') for s in 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.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list