[Tutor] Duplicate items in list

Alan Gauld alan.gauld at yahoo.co.uk
Tue Oct 20 12:59:33 EDT 2020


On 20/10/2020 16:06, Manprit Singh wrote:
> 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
This is you basically doing the for loops work for it!

There is a much simpler way to do this:


L = [2, 3, 3, 3, 6, 6, 7, 7, 3, 2, 2, 2, 9, 6]

prev = L[0]
print(prev)
for n in L[1:]:
    if prev != n:
        print(n)
        prev = n

No need to create iterators(the list is already iterable).

> Need your comments on the efficiency of this code .

No, you don't. As we have repeatedly said, use the interpreter.
It will tell you which is most efficient. Put the code you want
to compare into two functions. Then use the timeit module to
run both functions and see which is faster - ie. more efficient.
Then read again the advice about efficiency being less
important than readability in 99% of cases!

>>> def f():
    p = L[0]
    res = [p]
    for n in L[1:]:
        if res[-1] != n:
            res.append(n)
    return res

>>> import timeit as t

>>> t.timeit(f)

1.8774931590305641

If you similarly define your previous code as g() you
can compare the timings. That way we don't need to
guess or rely on anecdotal evidence, we can
measure the results.

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