• Register
1 vote


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


10 7 2
6,060 points

1 Answer

1 vote


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.

11 6 4
34,950 points

Related questions

1 vote
1 answer 18 views
Problem: Hello guys, I found python list is fun. I was doing some operation with a python list. Let me say, I have a python list looks: is_a_list = [1, 5, 3, 6, 3, 5, 6, 1] with mixed of duplicate values in it. Now, I am willing to remove all the duplicate elements from the list. How do you do that in an easiest and efficient way? I am eagerly waiting for your answers. Thanks.
asked Jun 25 adamSw 11.3k points
1 vote
1 answer 19 views
Problem : I have started learning python a few days ago . So I am doing my practice and I am getting cofused with some little things. Supose I have a list that is: listOfnumbers = [16, 22, 96, 15, 4, 39, 56, 40, 13, 22, 15] So what should I have to do to remove element from list python by index
asked Apr 3 LizzyM 6.1k points
0 votes
1 answer 31 views
Problem : How to remove all occurrences of a value from a list? I tried in Python remove() will remove the first occurrence of value in a list. How to remove all occurences?
asked Oct 22, 2019 peterlaw 6.9k points
0 votes
1 answer 3 views
Problem: I have following list that contains duplicate entries: America Britain England America Pakistan America Pakistan Britain Europe I want to remove duplicates from this list. How can I do this?
asked 6 days ago Sheeza 2.9k points
0 votes
2 answers 24 views
Problem: I am a newbee in python programming. I tried to remove all occurrences of a character in a list python. So I wrote a code: Nums = [11, 22, 11, 33, 11, 44, 11, 55] a = 11 print ("Original Numbers:") print (Nums) i=0 length = len(Nums) while(i< ... line 8, in <module> if(Nums[i]==a): IndexError: list index out of range Why I am getting this output but not the actual result. Please help
asked Mar 22 LizzyM 6.1k points