Best way to remove duplicate item from list in python

a = [1,2,1,2,1,5,1,2,2,2]
i want to remove all 2 from list.But what is the best way to do this?
my code:

a = [1,2,2,2,1,2,2,2,1,2]
for x in range(a.count(2)):
    a.remove(2)
print(a)

I’m looking for more fastest way.In list count(2) can be 50000 times.Then our loops will run 50000 times :frowning:

You can use set function to remove duplicates from a list

Actually i want to remove just 2 ._.

I’m not a python expert, but here’s one way to do it:

a = [1,2,2,2,1,2,2,2,1,2]

filtered_num_list = list(filter(lambda x: x != 2, a))

print(filtered_num_list)
1 Like

use simply list comprehension as follows.
a = [x for x in a if x != 2]

2 Likes