[Tutor] removing consecutive duplicates from list

Manprit Singh manpritsinghece at gmail.com
Tue Apr 20 22:38:15 EDT 2021


Dear all,

I am again writing few points :

I would prefer the solution given by Alan sir, as it seems easy to
understand and simple, not using any extra variable, and also not using any
module too like itertools.
Although I would like to thank dn for his comments, in which he has
strongly emphasised on enclosing solution code within a function, which is
a good practise.

Regards
Manprit Singh

On Tue, Apr 20, 2021 at 10:42 PM Alan Gauld via Tutor <tutor at python.org>
wrote:

> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list