While using the sum() function it adds the elements in the list and while the elements were inside quotation mark it rises an type error, while the overall type is an list. Why does it occurs, and how to overcome this problem.error while adding list a Describing the type
CodePudding user response:
The elements in quotation marks is of data type "String", whereas without quotation mark, it is treated as integer/float (int in this context). So, when you use sum it only works for int/float type.
Hence, you get error for string type.
CodePudding user response:
While you can "add" (concatenate) strings, sum
is intended for use with numerical values, in order to achieve a similar behavior but with strings, you can use str.join
:
>>> L = ['1', '2', '3', '4', '5']
>>> ''.join(L) # join the strings in `L` using the empty string '' as the connector
'12345'