Generate a list of strings with their lengths from another list


This Python code creates a list called word_lengths using a list comprehension to pair each word from the words list with its corresponding length (number of characters). 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: "apple," "banana," and "cherry."
  • word_lengths = [(word, 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 in the words list.
    • (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 words]: This is the list comprehension itself. It iterates through the words in the words list and, for each word, pairs it with its length and includes this pair (tuple) 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 = [(word, len(word)) for word in words]
print(words)
print(word_lengths)

Output

['apple', 'banana', 'cherry']
[('apple', 5), ('banana', 6), ('cherry', 6)]

Example Programs