Create a set of words with their characters sorted and concatenated


This Python code uses a set comprehension to create a set named sorted_concatenated, which contains words from the words list sorted and concatenated. Here's how the code works:

  • sorted_concatenated = {''.join(sorted(word)) for word in words}: This line initializes the set sorted_concatenated using a set comprehension.
    • for word in words: This part of the code iterates through each word in the words list.
    • ''.join(sorted(word)): It sorts the characters in the current word in alphabetical order, then joins them together using an empty string. This creates a word where the characters are sorted.
  • print(words): This line of code prints the original list of words, which is ["apple", "banana", "cherry"], to the console.
  • print(sorted_concatenated): This line of code prints the sorted_concatenated set, which contains words with characters sorted in alphabetical order, to the console.

Source Code

words = ["apple", "banana", "cherry"]
sorted_concatenated = {''.join(sorted(word)) for word in words}
print(words)
print(sorted_concatenated)

Output

['apple', 'banana', 'cherry']
{'aelpp', 'cehrry', 'aaabnn'}

Example Programs