Create a list of words with their lengths from a sentence
This Python code takes a sentence, splits it into words, and pairs each word with its corresponding length (number of characters). It then stores these pairs in a new list called word_lengths. Here's how the code works:
- sentence = "This is a sample sentence.": This line initializes a variable named sentence and assigns it the value "This is a sample sentence."
- word_lengths = [(word, len(word)) for word in sentence.split()]: This line of code initializes a variable named word_lengths and assigns it the result of a list comprehension.
- sentence.split(): This part of the code splits the sentence into a list of words. By default, it splits the sentence on whitespace, so it separates the words.
- for word in sentence.split(): This part sets up a loop that iterates through each word in the list of words.
- (word, len(word)): For each word in the list, this expression creates a tuple containing two elements: the original word word and the length of the word len(word) .
- [(word, len(word)) for word in sentence.split()]: This is the list comprehension itself. It iterates through the words in the sentence list, pairs each word with its length, and includes these pairs (tuples) in the new list.
- print(sentence): This line of code prints the original sentence to the console.
- print(word_lengths): This line of code prints the word_lengths list to the console.
Source Code
sentence = "This is a sample sentence."
word_lengths = [(word, len(word)) for word in sentence.split()]
print(sentence)
print(word_lengths)
Output
This is a sample sentence.
[('This', 4), ('is', 2), ('a', 1), ('sample', 6), ('sentence.', 9)]