Checking for palindrome words
This Python code creates a set named palindromes that contains palindromic words from a given list of words. Here's how the code works:
- words = ["radar", "hello", "level", "world"]: This line initializes a list named words with four words, some of which are palindromes and some are not.
- palindromes = {word for word in words if word == word[::-1]}: This line uses a set comprehension to create the palindromes set, containing only words from the words list that are palindromes.
- for word in words: This part of the code iterates through each word in the words list.
- if word == word[::-1]: It checks if each word is a palindrome. To determine this, it checks if the word is equal to its reverse (word[::-1]).
- print(words): This line prints the original words list to the console.
- print(palindromes): This line prints the palindromes set (which contains the palindromic words from the words list) to the console.
Source Code
words = ["radar", "hello", "level", "world"]
palindromes = {word for word in words if word == word[::-1]}
print(words)
print(palindromes)
Output
['radar', 'hello', 'level', 'world']
{'radar', 'level'}