Create a set of lengths of words in a sentence
This Python code processes a sentence, sentence, and creates a set, word_lengths, containing the lengths of words in the sentence. Here's how the code works:
- sentence = "This is a sample sentence.": This line initializes a variable named sentence and assigns it the string "This is a sample sentence."
- word_lengths = {len(word) for word in sentence.split()}: This line initializes a variable named word_lengths and assigns it a set created using a set comprehension. It splits the sentence into words using split() and iterates over each word, adding its length (number of characters) to the set.
- {...}: This notation is used to create a set.
- len(word) for word in sentence.split(): This part of the comprehension iterates over each word in the sentence after splitting it and calculates the length of each word using len(word).
- print(sentence): This line of code prints the original sentence to the console.
- print(word_lengths): This line of code prints the word_lengths set to the console.
Source Code
sentence = "This is a sample sentence."
word_lengths = {len(word) for word in sentence.split()}
print(sentence)
print(word_lengths)
Output
This is a sample sentence.
{1, 2, 4, 6, 9}