[Tutor] Duplicate items in list
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Oct 10 06:26:02 EDT 2020
On 10/10/2020 06:31, Manprit Singh wrote:
> Kindly suggest , if something can be done better:
>
> def remove_cons(lst):
> for i in range(len(lst)-1):
> if lst[i] != lst[i+1]:
> yield lst[i]
> yield lst[-1]
Any time you find yourself using indices to access
data in a Python for loop you can usually find
something better. It's nearly always the wrong thing
to do.
See Dennis' solution for a much cleaner option
that uses Python idioms.
--
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