Create a set of reversed strings from another set
This Python code uses a set comprehension to create a set named reversed_words containing the reversed versions of the words in the original set words. Here's how the code works:
- words = {"apple", "banana", "cherry"}: This line initializes a set named words containing three words: "apple," "banana," and "cherry."
- reversed_words = {word[::-1] for word in words}: This line initializes the set reversed_words 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 set.
- {word[::-1]}: For each word, this part includes its reverse (reversed string) in the reversed_words set. The word[::-1] slicing operation is used to reverse the word.
- print(words): This line of code prints the original words set to the console.
- print(reversed_words): This line of code prints the reversed_words set to the console.
Source Code
words = {"apple", "banana", "cherry"}
reversed_words = {word[::-1] for word in words}
print(words)
print(reversed_words)
Output
{'cherry', 'apple', 'banana'}
{'ananab', 'elppa', 'yrrehc'}