Sum of list of strings raises TypeError

Why are the following increasing in importance TypeError

? My list is uniform in type!

>>> a
['0', 'a']
>>> type(a[0])
<class 'str'>
>>> type(a[1])
<class 'str'>
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

      

+3


source to share


1 answer


The function sum

takes a second argument, the initial value of the accumulator. When not provided, it is assumed to be 0. So the first addition in your sum(a)

is equal 0 + '0'

, which results in a type error.

Instead, you want:



a = ['0', 'a']
print(''.join(a)) # '0a'

      

If you try to use sum

for strings, you will get an error to use instead ''.join(seq)

.

+9


source







All Articles