You could use a generator comprehension and the sum
function.
l = [[0,1,2],[3,4,5]]
print(sum(len(x) for x in l))
Maybe you could chain it even at a map
function:
l = [[0,1,2],[3,4,5],[4,5,6]]
print(sum(map(len,l)))
>>> 9
This could also be done by using the itertools.chain.from_iterable
function:
Alternate constructor for chain()
. Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:
def from_iterable(iterables):
# chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
for it in iterables:
for element in it:
yield element
This flattens a list of lists, making some iterable like [[0,1,2],[3,4,5]]
into something like [0,1,2,3,4,5]
, the lenght of the list above is the sum of the lenghts of the lists from the iterable above.
here is some code to test what said above:
import itertools
l = [[0,1,2],[3,4,5]]
print(len(itertools.chain.from_iterable(l)))
>>> 6