Create a set of words with their characters repeated twice


This Python code uses a set comprehension to create a new set named duplicated_chars, which contains words with duplicated characters from a list of words. Here's how the code works:

  • words = ["apple", "banana", "cherry"]: This line initializes a list named words with three string elements.
  • duplicated_chars = {''.join([char*2 for char in word]) for word in words}: This line initializes the set duplicated_chars using a set comprehension.
    • for word in words: This part of the code sets up a loop that iterates through each word in the words list.
    • for char in word: For each word, this part iterates through each character in the word and doubles it by using char*2.
    • ''.join(...): This part of the code combines the duplicated characters into a single string for each word.
  • print(words): This line of code prints the original list of words, words, to the console.
  • print(duplicated_chars): This line of code prints the duplicated_chars set to the console, containing the words with duplicated characters.

Source Code

words = ["apple", "banana", "cherry"]
duplicated_chars = {''.join([char*2 for char in word]) for word in words}
print(words)
print(duplicated_chars)

Output

['apple', 'banana', 'cherry']
{'aappppllee', 'bbaannaannaa', 'cchheerrrryy'}

Example Programs