Tuple of pairs of words and their lengths in Python


This Python code creates a tuple called word_lengths, which contains pairs of words and their corresponding lengths from the words list. Here's how the code works:

  • words = ["apple", "banana", "cherry", "date"]: This line initializes a variable named words and assigns it a list containing four words.
  • word_lengths = tuple((word, len(word)) for word in words): This line of code initializes a variable named word_lengths and assigns it a tuple created using a generator expression.
    • for word in words: This part of the code sets up a loop that iterates through each word word in the words list.
    • (word, len(word)): For each word, it creates a tuple containing the word itself word and its length len(word).
    • tuple(...): This surrounds the generator expression and converts the generated pairs of words and their lengths into a tuple.
  • 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 tuple (which contains pairs of words and their lengths) to the console.

Source Code

words = ["apple", "banana", "cherry", "date"]
word_lengths = tuple((word, len(word)) for word in words)
print(words)
print(word_lengths)

Output

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

Example Programs