Simple way to calculate the sum of all lengths of strings in a list

Viewed 350

I have lists that contain multiple strings like:

['beth', 'Nissan', 'apple', 'three']

I am searching for a short and easy way (inline if possible) to get the sum of all individual strings in this list. This is the code I currently have:

sum = 0
for string in list_of_strings:
    sum += len(string)
4 Answers

If you want the sum use:

result = sum([len(s) for s in list_of_strings])

If you are interested in the cummulative sum use:

import numpy as np

result = np.cumsum([len(s) for s in list_of_strings])

How about this

>>> strlist = ['beth', 'Nissan', 'apple', 'three']
>>> sum(len(x) for x in strlist)
20

You can use join to first concatenate the strings then calculate the length at once:

list_of_strings = ['beth', 'Nissan', 'apple', 'three']
len(''.join(list_of_strings))

Alternatively you can try this:

list_of_strings = ['beth', 'Nissan', 'apple', 'three']

s = sum(map(len, list_of_strings))
Related