How to remove duplicate items from a list using list comprehension?
Use keys
on a dict
constructed with values in a
as its keys.
b = dict([(i, 1) for i in a]).keys()
Or use a set:
b = [i for i in set(a)]
If you don't mind using a different technique than list comprehension you can use a set for that:
>>> a = [1, 2, 3, 3, 5, 9, 6, 2, 8, 5, 2, 3, 5, 7, 3, 5, 8]
>>> b = list(set(a))
>>> print b
[1, 2, 3, 5, 6, 7, 8, 9]
It's producing an identical list as b
contains no elements at run-time.
What you'd want it this:
>>> a = [1, 2, 3, 3, 5, 9, 6, 2, 8, 5, 2, 3, 5, 7, 3, 5, 8]
>>> b = []
>>> [b.append(item) for item in a if item not in b]
[None, None, None, None, None, None, None, None]
>>> b
[1, 2, 3, 5, 9, 6, 8, 7]