[Tutor] removing consecutive duplicates from list

Alan Gauld alan.gauld at yahoo.co.uk
Tue Apr 20 13:11:53 EDT 2021


On 20/04/2021 17:48, Manprit Singh wrote:

> The code that i have written to solve it, is written below:
> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4]
> ls = lst[1:]+[object()]
> [x for x, y in zip(lst, ls) if x != y]
> 
> The list comprehension gives the desired result. just need to know if this
> program can be done in a more readable and less complex way.

I'd suggest the more explicit form:

>>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4]
>>> result = []
>>> for idx,itm in enumerate(lst):
	if idx <= len(lst)-2 and itm == lst[idx+1]:
		continue
	result.append(itm)

You could write that as a list comprehension but I think
it loses readability.

>>> result2 = [itm for idx,itm in enumerate(lst)
	        if idx <= len(lst)-2 and itm != lst[idx+1]]

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