Create a list of words with their lengths from another list
This Python code takes a list of words and creates a new list called word_lengths using a list comprehension. The new list contains the lengths of the words in the original list. Here's how the code works:
- words = ["apple", "banana", "cherry"]: This line initializes a variable named words and assigns it a list containing three words.
- word_lengths = [len(word) for word in words]: This line of code initializes a variable named word_lengths and assigns it the result of a list comprehension.
- for word in words: This part sets up a loop that iterates through each word word in the words list.
- len(word): For each word in the list, this expression calculates the length of the word using the len() function. The len() function returns the number of characters (letters) in a string.
- [len(word) for word in words]: This is the list comprehension itself. It iterates through the words in the words list, calculates the length of each word, and includes these lengths in the new list.
- print(words): This line of code prints the original words list to the console.
- print(word_lengths): This line of code prints the word_lengths list to the console.
Source Code
words = ["apple", "banana", "cherry"]
word_lengths = [len(word) for word in words]
print(words)
print(word_lengths)
Output
['apple', 'banana', 'cherry']
[5, 6, 6]