views:

117

answers:

3

Is there a more idiomatic way to sum strings 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]
+11  A: 
length = sum(len(s) for s in strings)
liori
This is definitely a more idiomatic way of expressing it but I don't think it's any more efficient computationally. Still, +1 for elegance and Pythonicness!
Richard Cook
If you're really worried about computational efficiency, you probably shouldn't use Python, or should write the computation-intense part in C or C++ (or SciPy's weave library if you're brave). I like this style because it's more legible to other Python developers.
Mike DeSimone
Thanks, this is much shorter and easier to understand than my code.
Josh
+1  A: 
print(sum(len(mystr) for mystr in strings))
Tony Veijalainen
+7  A: 

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.

Daenyth
Good answer, but I've accepted [liori's answer](http://stackoverflow.com/questions/3780403#3780412) because I found it more idiomatic.
Josh
@Josh: Most people will indeed find the genexp more pythonic. I just wanted to add this for completeness.
Daenyth