Length of 2d list in python

python, python-2.7

Solution

`length = sum([len(arr) for arr in mylist])`

sum([len(arr) for arr in mylist[0:3]]) = 9
sum([len(arr) for arr in mylist[1:3]]) = 6
sum([len(arr) for arr in mylist[2:3]]) = 3

Sum the length of each list in `mylist` to get the length of all elements. This will only work correctly if the list is 2D. If some elements of `mylist` are not lists, who knows what will happen...

Additionally, you could bind this to a function:

len2 = lambda l: sum([len(x) for x in l])
len2(mylist[0:3]) = 9
len2(mylist[1:3]) = 6
len2(mylist[2:3]) = 3

Problem

I have a 2D list, for example `mylist =[[1,2,3],[4,5,6],[7,8,9]]`. Is there any way I can use `len()` function such that I can calculate the lengths of array indices? For example: ``` len(mylist[0:3]) len(mylist[1:3]) len(mylist[0:1]) ``` Should give: ``` 9 6 3 ```

Original source