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

为什么Python中禁止对字符串使用sum函数?

Why sum() fails with string lists in Python

At first glance, it makes total sense to assume any object with an __add__ method should work with sum()—and strings do implement __add__ for concatenation:

"abc" + "def"  # Returns "abcdef"

But here's the key detail that trips things up: sum() uses a default starting value of 0 (an integer). You can confirm this with quick tests:

sum([])       # Output: 0
sum([], 7)    # Output: 7

So when you run sum(["abc", "def"]), Python is actually doing this under the hood:

  1. Start with the default value 0
  2. Try to add the first string: 0 + "abc"

That's exactly why you get the error:

sum(["abc", "def"])  # Throws TypeError: unsupported operand type(s) for +: 'int' and 'str'

For what it's worth, you can force sum() to work for strings by passing an empty string as the starting value:

sum(["abc", "def"], "")  # Returns "abcdef"

But a quick heads-up—don’t use this in real code. str.join() is purpose-built for string concatenation and is way more efficient, especially with large lists.


内容的提问来源于stack exchange,提问作者patapouf_ai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:12:28