zhaoy zhaoy - 4 months ago 10
Python Question

Python list comprehension: list sub-items without duplicates

I am trying to print all the letters in all the words in a list, without duplicates.

wordlist = ['cat','dog','rabbit']
letterlist = []
[[letterlist.append(x) for x in y] for y in wordlist]


The code above generates
['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']
, while I am looking for
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
.

How do I modify the list comprehension to remove duplicates?

Answer

If you want to edit you own code:

[[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist]

or

list(set([[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist]))

else:

list(set(''.join(wordlist)))