Using Python, I'm trying to convert a sentence of words into a flat list of all distinct letters in that sentence.
Here's my current code:
words = 'She sells seashells by the seashore'
ltr = []
# Convert the string that is "words" to a list of its component words
word_list = [x.strip().lower() for x in words.split(' ')]
# Now convert the list of component words to a distinct list of
# all letters encountered.
for word in word_list:
for c in word:
if c not in ltr:
ltr.append(c)
print ltr
This code returns ['s', 'h', 'e', 'l', 'a', 'b', 'y', 't', 'o', 'r']
, which is correct, but is there a more Pythonic way to this answer, probably using list comprehensions/set
?
When I try to combine list-comprehension nesting and filtering, I get lists of lists instead of a flat list.
The order of the distinct letters in the final list (ltr
) is not important; what's crucial is that they be unique.