[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','')
print(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.

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