Create a set of unique characters from a list of words
This Python code uses a set comprehension to create a new set named unique_chars, which contains unique characters extracted from a list of words. Here's how the code works:
- words = ["apple", "banana", "cherry"]: This line initializes a list named words with three string elements.
- unique_chars = {char for word in words for char in word}: This line initializes the set unique_chars using a set comprehension.
- for word in words: This part of the code sets up a nested loop that iterates through each word in the words list.
- for char in word: For each word, this part iterates through each character in the word, and it adds each unique character to the unique_chars set.
- print(words): This line of code prints the original list of words, words, to the console.
- print(unique_chars): This line of code prints the unique_chars set to the console, containing the unique characters from the words.
Source Code
words = ["apple", "banana", "cherry"]
unique_chars = {char for word in words for char in word}
print(words)
print(unique_chars)
Output
['apple', 'banana', 'cherry']
{'y', 'a', 'e', 'c', 'b', 'p', 'l', 'n', 'h', 'r'}