为何列表推导式生成的列表为空?Python回文数生成报错排查
Hey there! No need to apologize at all—we all start somewhere, and it's awesome you're diving into Python and asking questions in English for the first time. Let's figure out this palindrome issue together!
What's Going Wrong?
You mentioned that when n=11, the list l = [int(i) for i in str(n)] ends up empty, which causes an IndexError when checking l[0] != l[-1]. That's strange because str(11) should be "11", so the list comprehension should definitely generate [1,1].
The most likely culprit is that somewhere in your is_palindrome(n) function, you're accidentally overwriting l to an empty list later on, or there's an indentation error that's making the list comprehension not run as expected.
A Simpler (and More Reliable) Approach
Instead of converting the number to a list of integers, you can work directly with the string representation of the number—this avoids index errors entirely and makes the code shorter:
def is_palindrome(n): s = str(n) return s == s[::-1] # Compare the string to its reverse # Now use it with filter palindromes = list(filter(is_palindrome, range(1, 1000))) print(palindromes)
Why This Works
str(n)converts the number to a string (e.g.,11becomes"11").s[::-1]creates a reversed copy of the string (e.g.,"11"reversed is still"11";"121"reversed is"121").- If the original string matches its reverse, it's a palindrome—simple as that!
Troubleshooting Your Original Code
If you want to fix your original list-based approach, add a print statement to debug what's happening to l:
def is_palindrome(n): l = [int(i) for i in str(n)] print(f"n={n}, str(n)={str(n)}, l={l}") # Check what l contains if l[0] != l[-1]: return False # Add any other checks for longer numbers here return True
Run this and look at the output for n=11—you'll probably see that l gets changed somewhere after the list comprehension. Common mistakes include:
- Accidentally reassigning
lto[]later in the function. - Indentation errors where the list comprehension isn't part of the
lassignment.
Final Result
Either way, using the string reversal method is the most straightforward way to check for palindromes in Python, and it'll prevent those annoying index errors.
内容的提问来源于stack exchange,提问作者William

