jef
jef

Reputation: 4083

Sum of each element's length in Python

How to calculate sum of each element of list in python3? Although I could do it, are there any smart ways?

data = [[1,2],[1], [3,4,2]]
sum_length = 0
for d in data:
    sum_length += len(d)
print(sum_length) # 6

Upvotes: 1

Views: 1779

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226336

The shortest and fastest way is apply a functional programming style with map() and sum():

>>> data = [[1,2],[1], [3,4,2]]
>>> sum(map(len, data))
6

In Python 2, use itertools.imap instead of map for better memory performance:

>>> from itertools import imap
>>> data = ['a', 'bc', 'def', 'ghij']
>>> sum(imap(len, data))
10

Upvotes: 6

Related Questions