Generate a list of numbers that are palindromes from 1 to 100
This Python code generates a list called palindromes using a list comprehension. The list contains numbers from 1 to 100 that are palindromes when their digits are reversed. Here's how the code works:
- palindromes = [x for x in range(1, 101) if str(x) == str(x)[::-1]] : This line of code initializes a variable named palindromes and assigns it the result of a list comprehension.
- for x in range(1, 101): This part sets up a loop that iterates through numbers from 1 to 100 (inclusive). It generates values for x.
- str(x) == str(x)[::-1]: For each number in the range, this expression converts x to a string using str(x) , then checks if the string representation of x is equal to its reverse, achieved by str(x)[::-1]. This comparison determines whether x is a palindrome or not.
- [x for x in range(1, 101) if str(x) == str(x)[::-1]]: This is the list comprehension itself. It iterates through the numbers in the specified range (1 to 100), checks if each number is a palindrome, and includes palindromic numbers in the new list.
- print(palindromes): This line of code prints the palindromes list to the console.
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, 11, 22, 33, 44, 55, 66, 77, 88, 99]