• Register
1 vote
44 views

Problem:

Can anyone tell me the best way to remove duplicates from list keep order in python.
Thank you.

 

6.1k points

Please log in or register to answer this question.

1 Answer

1 vote

Answer:

The best way to remove duplicates from list keep order by using this code in python;

def pata(seq):
    seen = set()
    seen_add = seen.add
    return [a for a in seq if not (a in seen or seen_add(a))]

Explanation why use this:

I assigned seen.add to seen_add instead of just calling seen.add because Python is a dynamic language, and resolving seen.add each iteration is more costly than resolving a local variable. seen.add could have been changed between iterations, and the runtime isn't smart enough to rule that thing out and it has to check the object each time.

Hope this helps you.

35k points