You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何列表推导式生成的列表为空?Python回文数生成报错排查

Fixing the IndexError in Your Palindrome Filtering Code

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., 11 becomes "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 l to [] later in the function.
  • Indentation errors where the list comprehension isn't part of the l assignment.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:26:52