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)
CodePudding user response:
How about this
>>> strlist = ['beth', 'Nissan', 'apple', 'three']
>>> sum(len(x) for x in strlist)
20
CodePudding user response:
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])
CodePudding user response:
Alternatively you can try this:
list_of_strings = ['beth', 'Nissan', 'apple', 'three']
s = sum(map(len, list_of_strings))
CodePudding user response:
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))