Is there a more idiomatic way to sum string lengths in Python than by using a loop?
length = 0
for string in strings:
length += len(string)
I tried sum()
, but it only works for integers:
>>> sum('abc', 'de')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Here's another way using operator. Not sure if this is easier to read than the accepted answer.
Just to add upon ...
Adding numbers from a list stored as a string
nos = ['1','14','34']
length = sum(int(s) for s in nos)
I know this is an old question, but I can't help noting that the Python error message tells you how to do this:
So:
My first way to do it would be
sum(map(len, strings))
. Another way is to use a list comprehension or generator expression as the other answers have posted.