Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sum string lengths

Tags:

python

list

sum

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]
like image 825
Zaz Avatar asked Sep 23 '10 16:09

Zaz


3 Answers

length = sum(len(s) for s in strings)
like image 127
liori Avatar answered Sep 28 '22 21:09

liori


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.

like image 36
Daenyth Avatar answered Sep 28 '22 21:09

Daenyth


I know this is an old question, but I can't help noting that the Python error message tells you how to do this:

TypeError: sum() can't sum strings [use ''.join(seq) instead]

So:

>>> strings = ['abc', 'de']
>>> print len(''.join(strings))
5
like image 30
Auspex Avatar answered Sep 28 '22 21:09

Auspex