Set of words with a given prefix


This Python code creates a set named words_with_prefix that contains words from a given list of words that start with a specified prefix. Here's how the code works:

  • words = ["apple", "banana", "cherry", "date"]: This line initializes a list named words with four words.
  • prefix = "ba": This line initializes a string variable named prefix with the prefix you want to search for.
  • words_with_prefix = {word for word in words if word.startswith(prefix)}: This line uses a set comprehension to create the words_with_prefix set. It iterates through each word in the words list and includes it in the words_with_prefix set if it starts with the specified prefix.
    • for word in words: This part of the code iterates through each word in the words list.
    • if word.startswith(prefix): It checks whether each word starts with the specified prefix.
  • print(words): This line prints the original words list to the console.
  • print(prefix): This line prints the specified prefix to the console.
  • print(words_with_prefix): This line prints the words_with_prefix set, which contains the words that start with the specified prefix.

Source Code

words = ["apple", "banana", "cherry", "date"]
prefix = "ba"
words_with_prefix = {word for word in words if word.startswith(prefix)}
print(words)
print(prefix)
print(words_with_prefix)

Output

['apple', 'banana', 'cherry', 'date']
ba
{'banana'}

Example Programs