You get an error because you're referencing res
inside the comprehension. This doesn't work, since res
is only available after the expression is finished.
As I'm a curious sort, and because the title asks "Removing duplicates from list of lists by using list comprehension", I wanted to see if you can do this using only a list comprehension, and not by cheating such as using itertools
:p
And here's how:
>>> lists = [ [ "a","b","c" ],[ "d","a" ],[ "c","a","f" ] ]
>>> lists2 = sorted(sum(lists, []))
>>> [ item for i, item in enumerate(lists2) if i == 0 or i == len(lists2) or lists2[i - 1] != item ]
['a', 'b', 'c', 'd', 'f']
For more insanity, you can combine them on a single line, but you'd have to repeat the sum()
and sorted()
calls. I couldn't move myself to write such ugly code ;-)
sum(lists, [])
will flatten the list; it returns the sum (+
operator) of all the items in lists
, with []
as the initial list.
sorted()
will sort it. This is needed since we only check against the last item
- the
if
statement checks if the previous item is the same as the current item.
But it's ugly and un-Pythonic. For the love of Guido, use Pythonista's answer (or some variation thereof)!