Create a set of numbers that are palindromes from 1 to 100


This Python code uses a set comprehension to create a set named palindromes, which contains palindromic numbers within the range from 1 to 100. Here's how the code works:

  • palindromes = {x for x in range(1, 101) if str(x) == str(x)[::-1]}: This line initializes the set palindromes using a set comprehension.
    • for x in range(1, 101): This part of the code iterates through numbers from 1 to 100 (inclusive).
    • if str(x) == str(x)[::-1]: This part of the code checks if a number is a palindrome. It does this by converting the number x to a string using str(x). Then, it checks if the string representation of the number is equal to its reverse, obtained using slicing str(x)[::-1].
  • print(palindromes): This line of code prints the palindromes set to the console, which contains the palindromic numbers within the specified range.

Source Code

palindromes = {x for x in range(1, 101) if str(x) == str(x)[::-1]}
print(palindromes)

Output

{1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 11, 44, 66, 77, 99, 22, 55, 88}

Example Programs