[Tutor] Ways of removing consequtive duplicates from a list
Manprit Singh
manpritsinghece at gmail.com
Sat Jul 16 05:26:22 EDT 2022
Dear Sir ,
I was just doing an experiment of removing consecutive duplicates from a
list . Did it in the following ways and it all worked . Just need to know
which one should be preferred ? which one is more good ?
lst = [2, 2, 3, 3, 3, 2, 2, 5, 5, 6, 3, 3, 3, 3]
# Ways of removing consequtive duplicates
[ele for i, ele in enumerate(lst) if i==0 or ele != lst[i-1]]
[2, 3, 2, 5, 6, 3]
val = object()
[(val := ele) for ele in lst if ele != val]
[2, 3, 2, 5, 6, 3]
import itertools
[val for val, grp in itertools.groupby(lst)]
[2, 3, 2, 5, 6, 3]
Is there anything else more efficient ?
Regards
Manprit Singh
More information about the Tutor
mailing list