Create a list of words with their lengths greater than 3 from a sentence
This Python code takes a sentence, splits it into words, and creates a new list called long_words containing only words with more than 3 characters. 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."
- long_words = [word for word in sentence.split() if len(word) > 3] : This line of code initializes a variable named long_words 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.
- if len(word) > 3: This is a condition that checks whether the length (number of characters) of the current word word is greater than 3.
- [word for word in sentence.split() if len(word) > 3]: This is the list comprehension itself. It iterates through the words in the sentence list, includes only those words with a length greater than 3, and includes them in the new list.
- print(sentence): This line of code prints the original sentence to the console.
- print(long_words): This line of code prints the long_words list to the console.
Source Code
sentence = "This is a sample sentence."
long_words = [word for word in sentence.split() if len(word) > 3]
print(sentence)
print(long_words)
Output
This is a sample sentence.
['This', 'sample', 'sentence.']