[Tutor] Duplicate items in list

Manprit Singh manpritsinghece at gmail.com
Tue Oct 20 11:06:22 EDT 2020


Dear sir ,

I have written some code for the same problem . Need your comments on the
efficiency of this code :


l = [2, 3, 3, 3, 6, 6, 7, 7, 3, 2, 2, 2, 9, 6]
it = iter(l)
ini = next(it)
print(ini)
for i in it:
    if i != ini:
        print(i)
        ini = i

It removes all consecutive duplicates . I am getting the correct answer
See if you remember, we had a discussion on when to use None or object()
for a variable that was initialized in the beginning of for loop . This
code eliminated the need for the same . Need your comments on the
efficiency of this code .

Regards
Manprit singh


On Fri, Oct 9, 2020 at 9:07 PM Manprit Singh <manpritsinghece at gmail.com>
wrote:

> Dear sir,
>
> Consider a list as given below :
>
> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5]
> I need to print the values  as given below  and in same order:
>
> 3       # print 3 only once as there are two occurrence of 3 in the
> beginning  in list
> 5       # print 5 only once as there are 3 occurrence of 5 after 3 in the
> list
> 6       # print 6 only once as there are 3 occurrence of 6 after 5 in the
> list
> 5       # print 5 only once as there is single occurrence of 5 after 6 in
> the list
> 9       # print 9 only once as there is single occurrence of 9 after 5 in
> the list
> 3       # print 3 only once as there  are 3 occurrence of 3 after 9 in the
> list
> 5       # print 5 only once as there are 2 occurrence of 5 in the last
>
> I have written the code as given below:
> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5]
> for i, j in enumerate(lst[:-1]):
>     if lst[i+1] != j:
>         print(j)
> print(lst[-1])
>
> which gives the answer as given above
> I feel that a better code can be written for this problem , Need your
> guidance.
>
> Regards
> Manprit singh
>
>
>


More information about the Tutor mailing list